How To Increment JQuery Element ID
Solution 1:
The problem is that all those "playAnswer" functions are wrapped around the very same "i" variable. That is, there's only one "i" (and in this case, since you didn't declare it with var
, it's global!).
What you need to do is use another function to provide a separate "i" for each one of the callbacks.
function addPlayAudioMethodToExerciseArray(){
function makePlayerCallback(i) {
return function() {
$('#jPlayer' + i).jPlayer('play', 0);
};
}
for (var i = 0; i < qaArray.length; ++i){
qaArray[i].playAnswer = makePlayerCallback(i);
}
}
The "makePlayerCallback" function has its own parameter "i", which, being effectively local to that function, will result in callback functions that have their own "i" individually. Each call to that function creates what's called a "closure" around the returned callback function. (Note that my loop starts at zero; if your identifiers in the HTML start at 1, you'll need to account for that by adding 1 somewhere. Thanks to @DieVarDump for that note.)
Note that I declared the "i" used in the loop with var
to make it local to "addPlayAudioMethodToExerciseArray" (boy that's a long function name; I hope you won't have to type it too often :-). Also, I used it as a numeric index, under the assumption that"qaArray" is really an honest-to-gosh array, and not just n object. It's good practice to use numeric indexing for arrays.
Solution 2:
use colsures
try this :
for(i in qaArray)
{
qaArray[i].playAnswer = function (num)
{
return function ()
{
$('#jPlayer' + num).jPlayer('play', 0);
} ;
}(i)
};
Post a Comment for "How To Increment JQuery Element ID"