Jquery add parameter to function in for loop
I have this:
$.ajax({
url: "blah.php?something",
dataType: "json"
....
success: function(x){
for(i in x.artists) {
addbutton.text(x.artists[i].name).click(function(){
load(x.artists[i].name)
});
}
});
It's for a music player, and this is a suggestions engine. It loads artist names through AJAX, in JSON format from the PHP file, as you can see.
The problem is with the click() function which is supposed to load songs related to that artist. When t开发者_JAVA技巧he function gets called (ie the button gets clicked), instead of passing the artist's name as a string to load(), it passes x.artists[i].name, which of course is invalid outside of the ajax success function.
How would I go about solving this?
Thanks, Fela
Replace
load(x.artists[i].name)
with
load($(this).text())
Change your addButton click handler to:
addbutton.text(x.artists[i].name).click(function(){
load($(this).text())
});
or change the for loop to as follows(in case the text of the button is changed by some other code before the button is clicked.):
for(i in x.artists) {
var artistName = x.artists[i].name;
addbutton.text(artistName ).click(function(){
load(artistName) ;
});
}
Seeing as how you are setting the text value first - you can just re-use that if you like:
addbutton.text(x.artists[i].name).click(function(){ load($(this).text()) })
精彩评论