为什么``each`方法中的`index`参数表现不同?

时间:2013-11-20 17:37:01

标签: javascript jquery indexing each

为什么index方法中的each参数在这种情况下的行为有所不同?

http://jsfiddle.net/4h4fy/1/

$('li').each(function(index) {
    $('li').text(index);// This prints only 2s 
    console.log(index);// This prints 0, 1, 2 
});

我如何才能获得它,以便在<li>标签旁边打印0,1,2?

3 个答案:

答案 0 :(得分:5)

尝试:

$('li').each(function(index) {
    $(this).text(index);
});

只需在$('li')内传递.each(),就无法正确捕捉上下文。您需要改为使用$(this)

这里的工作示例:http://jsfiddle.net/G7ZnM/1/

答案 1 :(得分:4)

每次进行循环时,都会将每个 li的文本设置为当前索引。所以最终它们都会被设置为最后一个索引。

请改为尝试:

$('li').each(function(index, item) {
    $(item).text(index); // This prints 0, 1, 2 
});

答案 2 :(得分:1)

使用'this'来指代当前'li':

$('li').each(function(index) {
    $(this).text(index);// This prints 0,1,2
    console.log(index);// This prints 0, 1, 2 
});