How To Increment jQuery Element ID

陌路散爱 提交于 2019-12-11 23:09:01

问题


I have instances of jPlayer (jquery audio player): jPlayer1, jPlayer2, jPlayer3, jPlayer4, each initialized and preloaded with audio files.

Calling function below will traverse an existing array and adding the methods that plays the preloaded audio.

function addPlayAudioMethodToExerciseArray(){
    for (i in qaArray){
        qaArray[i].playAnswer = function(){ $('#jPlayer'+i).jPlayer('play',0);}
    }
}  

It creates the method alright except for the part ('#jPlayer'+i) is not evaluated to become ('#jPlayer1'), ('#jPlayer2'), etc.

Many thanks in advance. Note: I'm a noob.


回答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.




回答2:


use colsures

try this :

    for(i in qaArray)
    {
        qaArray[i].playAnswer = function (num)
        {
            return function ()
            {
                $('#jPlayer' + num).jPlayer('play', 0);
            } ;
        }(i)
    };


来源:https://stackoverflow.com/questions/9045905/how-to-increment-jquery-element-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!