Javascript jQuery在每个$范围内突破$
我需要迭代AJAX响应,并在满足条件时中断事件处理程序。我在使用此代码时遇到问题:Javascript jQuery在每个$范围内突破$,javascript,jquery,break,Javascript,Jquery,Break,我需要迭代AJAX响应,并在满足条件时中断事件处理程序。我在使用此代码时遇到问题: $.each(response, function(i, v) { // create mapbox object var map = L.mapbox.map('map', v.map_embed_id, { zoomAnimation: false }); var polygonLayer = L.mapbox.featureLayer().loadURL(
$.each(response, function(i, v) {
// create mapbox object
var map = L.mapbox.map('map', v.map_embed_id, {
zoomAnimation: false
});
var polygonLayer = L.mapbox.featureLayer().loadURL('https://a.tiles.mapbox.com/v4/' + v.map_embed_id + '/features.json?access_token=abcde').addTo(map);
polygonLayer.on('ready', function() {
var layer = leafletPip.pointInLayer(latlng, polygonLayer, true);
if (layer.length) {
// this is where I need to break out of $.on
// and the current $.each iteration
}
});
});
我知道返回false会在每次迭代中突破$。但这更困难,因为我需要在事件处理程序中突破$。我能做什么?我可以使用触发器吗?多亏@Kevin B建议使用递归,这就是我修复代码的方法
getMapsList().done(function(maps) {
getMapboxMap(maps, geocode);
});
function getMapboxMap(maps, geocode) {
var map_params = maps[0];
var map_embed_id = map_params.map_embed_id;
if (maps.length > 0)
maps.shift();
// create mapbox object
var map = L.mapbox.map('map', map_embed_id, {
zoomAnimation: false
});
// create marker of address entered
L.mapbox.featureLayer({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [
geocode.location.lng,
geocode.location.lat
]
},
properties: {
title: address,
'marker-size': 'medium',
'marker-color': '#f44',
'marker-symbol': 'star'
}
}).addTo(map);
// create polygon layer and add to map from map's geojson
var polygonLayer = L.mapbox.featureLayer().loadURL('https://a.tiles.mapbox.com/v4/' + map_embed_id + '/features.json?access_token=pk.eyJ1IjoiZW5nbGVzaWRldGVycml0b3JpZXMiLCJhIjoiekFIU0NlayJ9.rE9XdicgXc9aIiXJ9yn68w').addTo(map);
// after polygon layer has been added to map
polygonLayer.on('ready', function() {
// featureLayer.getBounds() returns the corners of the furthest-out markers,
// and map.fitBounds() makes sure that the map contains these.
map.fitBounds(polygonLayer.getBounds());
// create a latLng object based on lat/lng of address entered
var latlng = L.latLng(geocode.location.lat, geocode.location.lng);
// create point in layer object
var layer = leafletPip.pointInLayer(latlng, polygonLayer, true);
if (layer.length) {
// found it
return false;
} else {
if (maps.length > 0) {
getMapboxMap(maps, geocode);
}
}
});
}
function getMapsList() {
return $.get('/utility/territories/maps-list');
}
是否确实需要为每个迭代的每个迭代绑定事件?这看起来有点可疑,可能就是我要解决的问题。可以用于事件处理程序并为每个事件返回false为什么要绑定就绪事件?你认为它能做什么?在这些事件被触发之前,每一个都会被完成。这里错的太多了。确保你发布了一个答案,展示了什么对未来的访问者有帮助