javascript increment index in function
I'm just trying to figure out how to create an index inside a function so I can keep track of the items its generating and I'm not sure how to do this seems like I should know this..
addLocation(options,location)
funciton addLocation(options,location){
$('#list').append('<li class="location"><div>'+location.label+'</div>'+
'<input type="hidden" name="location['+x+'][lat]" value="'+location.lat+'" />'+
'<input type="hidden" name="location['+x+'][lon]" value="'+location.lon+'" />'+
'<input type="hidden" name="location['+x+'][loc]" value="'+location.loc+'" />'+
'<input type="hidden" name="location['+x+'][label]" value="'+location.label+'" />'+
'</li>');
}
now normally you have a forloop to help you keep track of things but int this instance I'm not appending items in a loop and I keep getting an error saying x in undefined
ap开发者_Go百科preciate any help you can give
thanks Mike
Since what you want is that each time the function is called, x
should be incremented, you can store x
in a closure, for example:
var addLocation = (function (){
var x = 0; // store x
return function (options,location) {
x++; // increment x
$('#list').append('<li class="location"><div>'+location.label+'</div>'+
'<input type="hidden" name="location['+x+'][lat]" value="'+location.lat+'" />'+
'<input type="hidden" name="location['+x+'][lon]" value="'+location.lon+'" />'+
'<input type="hidden" name="location['+x+'][loc]" value="'+location.loc+'" />'+
'<input type="hidden" name="location['+x+'][label]" value="'+location.label+'" />'+
'</li>');
};
})();
Declare x since in your above code it's not defined.
var x = 0;
var x = $("#list>li").length + 1;
精彩评论