I need some help regarding jquery arrays.
var queryArr;
$(markersArray).each(function(index) {
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
//I DO NOT KNOW THE SYNTAX BELOW HELP IN HERE PLEASE..
var locations = {
locationId:_locationId;
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations} //??????????
});
queryArr.push(location); //???????
}
I need to reach each element by using sth like this:
alert(queryArr[0].locations.locationId);
开发者_如何学GoObviously I will be using a for loop to reach each data by an index.
Can anyone give me example syntax for this.. I have found plenty examples of fixed arrays but not dynamic content.
You're very close. The line with push needs to be moved inside the .each() loop and you need to use queryStr for the push. Make sure you don't have any other syntax errors like missing semicolons.
queryArr.push(queryStr);
Here's your example:
var queryArr = [];
$(markersArray).each(function(index) {
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
"locationId" :_locationId;
"locationName" :_locName,
"lat" :_markerLat,
"lng" :_markerLng
};
queryStr = { "locations" : locations };
queryArr.push(queryStr);
});
var elements = document.getElementsByTagName("div"); // returns a nodeList
var array = jQuery.makeArray(elements );
$(array ).appendTo(document.body);
or like
var object = $('li');
var array = $.makeArray(object);
var queryArr=[];
for ( var index=0; index<markersArray.length; index++){
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
locationId:_locationId,
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations}
queryArr.push(queryStr);
}
//test - works:)
for ( var i=0; i<markersArray.length; i++){
alert(
queryArr[i].locations.locationId+"--"+
queryArr[i].locations.locationName +"--"+
queryArr[i].locations.lat);
}
精彩评论