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

时间:2021-03-03 19:23:00

Why does the index parameter in the each method behave differently in this scenario?

为什么在这种情况下,每种方法中的索引参数的行为都不同?

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

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

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

How I can I get it so that 0, 1, 2 prints along side the <li> tags?

我怎么能得到它,以便在

  • 标签旁边打印0,1,2?

  • 标签旁边打印0,1,2?
  • 3 个解决方案

    #1


    5  

    Try:

    尝试:

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

    Simply passing your $('li') within a .each() won't capture the context correctly. You need to use $(this) instead.

    简单地在.each()中传递$('li')将无法正确捕获上下文。你需要使用$(this)代替。

    And the working example here: http://jsfiddle.net/G7ZnM/1/

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

    #2


    4  

    Each time you go through the loop, your setting the text for every li to current index. So in the end they will all be set to whatever the last index was.

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

    Try this instead:

    试试这个:

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

    #3


    1  

    Use 'this' to refer to current 'li' :

    使用'this'来表示当前'li':

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

    #1


    5  

    Try:

    尝试:

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

    Simply passing your $('li') within a .each() won't capture the context correctly. You need to use $(this) instead.

    简单地在.each()中传递$('li')将无法正确捕获上下文。你需要使用$(this)代替。

    And the working example here: http://jsfiddle.net/G7ZnM/1/

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

    #2


    4  

    Each time you go through the loop, your setting the text for every li to current index. So in the end they will all be set to whatever the last index was.

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

    Try this instead:

    试试这个:

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

    #3


    1  

    Use 'this' to refer to current 'li' :

    使用'this'来表示当前'li':

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