如何增加jQuery元素ID [英] How To Increment jQuery Element ID

查看:95
本文介绍了如何增加jQuery元素ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有jPlayer(jquery音频播放器)的实例:jPlayer1,jPlayer2,jPlayer3,jPlayer4,每个实例均已初始化并预加载了音频文件.

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);}
    }
}  

它会创建方法,除了部分('#jPlayer'+ i)不被评估为('#jPlayer1'),('#jPlayer2')等之外.

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.

推荐答案

问题是所有这些"playAnswer"函数都包裹在相同的"i"变量周围.也就是说,只有一个"i"(在这种情况下,因为您没有使用var进行声明,所以它是全局的!).

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!).

您需要做的是使用另一个函数为每个回调提供单独的"i".

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);
    }
}

"makePlayerCallback"函数具有其自己的参数"i",该参数实际上是 that 函数的局部变量,将导致回调函数分别具有其自身的"i".对该函数的每次调用都会在返回的回调函数周围创建所谓的关闭". (请注意,我的循环从零开始;如果HTML中的标识符从1开始,则需要在某处添加1来解决这个问题.感谢@DieVarDump提供了该注释.)

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.)

请注意,我用var声明了循环中使用的"i",使其在"addPlayAudioMethodToExerciseArray"中是本地的(男孩是一个长函数名;我希望您不必过于频繁地键入它:-) .另外,在"qaArray"实际上是一个诚实的数组,而不仅仅是n个对象的假设下,我将其用作数字索引.对数组使用数字索引是个好习惯.

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.

这篇关于如何增加jQuery元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆