最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery each() function - Stack Overflow

programmeradmin5浏览0评论

Given list

<ul>
    <li>aaa</li>
    <li>sss</li>
    <li>ddd</li>
</ul>

js code:

$(document).ready( function () {

    $("ul li").each( function () {

          $("ul").empty();

          alert( $(this).text() );        

    });

});

This code returns every element normally, Why? Why list is not cleared at first iteration?

Given list

<ul>
    <li>aaa</li>
    <li>sss</li>
    <li>ddd</li>
</ul>

js code:

$(document).ready( function () {

    $("ul li").each( function () {

          $("ul").empty();

          alert( $(this).text() );        

    });

});

This code returns every element normally, Why? Why list is not cleared at first iteration?

Share Improve this question edited Mar 25, 2013 at 11:21 frenchie 52.1k117 gold badges320 silver badges528 bronze badges asked Mar 25, 2013 at 11:19 Oto ShavadzeOto Shavadze 43k55 gold badges166 silver badges246 bronze badges 3
  • The .each() function creates a closure: that's what it's all about. – frenchie Commented Mar 25, 2013 at 11:22
  • Nothing to do with the question, but try to use console.log( $(this).text() ); so that you don't have to click the alert() away each time. On topic: If you don't need to do certain action on <li> items, just do $("ul li").empty();. – user1467267 Commented Mar 25, 2013 at 11:23
  • var myList = []; $("ul li").each(function(){ myList[myList.length] = $(this).html(); }); $("ul li").empty(); console.log(myList); with this code you will store the innerHTMLs for re-usage and still can empty them all. Might not be what you want, but I'm trying to show workarounds for your (possible) problem. – user1467267 Commented Mar 25, 2013 at 11:29
Add a ment  | 

2 Answers 2

Reset to default 8

The unordered list is indeed cleared in your first iteration, but the list items are still referenced by the jQuery object you created with $("ul li").

They may not be part of the DOM anymore, but they still exist in memory, and you can still access and manipulate them.

The .each() function creates a closure: that's what closures are all about.

When the line $("ul").empty(); executes, it clears the reference to the list but because the same list is ALSO referenced with this, the list is still there, just not referenced with $("ul li") anymore.

发布评论

评论列表(0)

  1. 暂无评论