Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 通过for循环添加click事件_Jquery - Fatal编程技术网

Jquery 通过for循环添加click事件

Jquery 通过for循环添加click事件,jquery,Jquery,这段代码运行良好——单击第一个(li)得到“0”,单击第二个(li)得到“1” 然而,我宁愿使用for循环。使用以下各项,每个(li)产生“2” for(变量i=0;i

这段代码运行良好——单击第一个(li)得到“0”,单击第二个(li)得到“1”

然而,我宁愿使用for循环。使用以下各项,每个(li)产生“2”

for(变量i=0;i<2;i++){
$(“li”).eq(i)。单击(函数(){alert(i)});
}

为什么??提前谢谢。如果这是显而易见的,我很抱歉,但这让我发疯。

变量i是一个全局变量。在for循环之后,它的值为2,每次单击任何li元素时,它都会提醒i的值,现在为2

尝试:

for(变量i=0;i<2;i++){
$('li').eq(i).单击(函数(){
警报($(this.index());
});        
}

使用jQuery
index()
方法要简单得多,它不需要
进行循环:

$('li').click(function(){ 
   /* "this " is element clicked*/       
    alert( $(this).index() );
});
使用不带参数的
index()
将返回与其同级元素相关的元素索引。还有一些方法可以对其他元素集合使用
index()

API参考资料:

闭包是个婊子:) 您应该这样做-这将捕获“正确的”i

函数createAlertFunction(i){
返回(函数onClickFunc(){
警报(一)
});
}
对于(变量i=0;i<2;i++){
$(“li”).eq(i).单击=createAlertFunction(i);
}

这称为闭包。执行此操作时,您正在设置一个名为
i
的全局变量。因此,当您单击它时,
click
函数会记住这个变量,它总是2,因为它是循环结束时的值

现在为什么它是一个globa变量呢?因为javascript有函数scop而不是块作用域

<script type="text/javascript">
    var imGlobal = "Hello!";
    // ^ Watch out for the scope! I'm NOT inside a function

    for (var i = 0; i < 2; i++){}
    // ^ Watch out for the scope! I'm NOT inside a function EITHER!!!

    function(){
        // ^ Watch out for the scope! I'm inside a function
        var imNOTGlobal = "I won't exist after the function has returned (under certain circumstances ;])";
    }();
    console.log(imGlobal);    //"Hello!"
    console.log(i);           //2
    console.log(imNOTGlobal); //undefined
</script>
每次调用该函数时,它都会检查它是否已经计算出第n个素数,并将其存储在一个数组中,该数组可用于闭包,这样就不必每次向函数询问第n个素数时都进行计算

现在,这有什么用呢?:您可以使用一个变量,它不是每次调用
getPrimeNumber()时都初始化的并且此变量不是全局对象


注意:该函数不起作用,但说明了这一点。

为什么不直接执行
$(“li”)。单击(函数(){alert($(this).index())})这可能会起作用,但是如果for循环做了超出本文范围的其他事情,该怎么办呢。我想他是想弄明白为什么变量不能“粘住”,不是因为他真的想提醒LI的索引。@HighParkCoder这当然是一个观点,我个人相信OP会从这些知识和代码简化中受益。不管循环中的其他功能如何,OP显示的关系与
index()
Closure是javascript执行以下有用操作的一种方式:…像什么?@HighParkCoder抱歉,它没有剩下的部分就进入了:S
for (var i = 0; i < 2; i++) {
   $('li').eq(i).click(function() { 
         alert( $(this).index() ); 
    });        
}
$('li').click(function(){ 
   /* "this " is element clicked*/       
    alert( $(this).index() );
});
function createAlertFunction(i) {
    return (function onClickFunc () {
        alert(i)
    });
}

for (var i = 0; i < 2; i++) {
    $("li").eq(i).click = createAlertFunction(i);
}
<script type="text/javascript">
    var imGlobal = "Hello!";
    // ^ Watch out for the scope! I'm NOT inside a function

    for (var i = 0; i < 2; i++){}
    // ^ Watch out for the scope! I'm NOT inside a function EITHER!!!

    function(){
        // ^ Watch out for the scope! I'm inside a function
        var imNOTGlobal = "I won't exist after the function has returned (under certain circumstances ;])";
    }();
    console.log(imGlobal);    //"Hello!"
    console.log(i);           //2
    console.log(imNOTGlobal); //undefined
</script>
// To get the nth prime number
var getPrimeNumber = function (){
    var primeNumbers = [];
    return function(n){
        if(!primeNumbers[n]){
            // Calculate the nth prime number and insert it into the array.
        }

        return primeNumbers[n];
    };
}(); // The function is executed immediately 
// making "var getPrimeNumber" to hold the result of the execution 
// which is a function that remembers primeNumbers 
// and is who does the actual calculation

getPrimeNumber(1);
getPrimeNumber(2);
getPrimeNumber(3); // Calculate it the first time
getPrimeNumber(4);
getPrimeNumber(3): // This is already calculated!
// The array ends up with 4 slots;