开发者

problem with jquery each

I'm trying to make a dynamic list with jquery. What i have is an ul element that contains a link and a sub ul element. Like this:

<div id="new_list"></div>
<ul id="old_list" class="listview">
    <li>
      <a class="list" href="#">List I</a>
      <ul class="sub">
        <li>1</li>
        <li>2</li>
      </ul>
    </li>
    <li>
      <a class="list" href="#">List II</a>
      <ul class="sub">
        <li>1</li>
        <li>2</li>
      </ul>
    </li>
</ul>

What i want to do with this list is:

when user clicks any of these links, the sub ul element's html( which is the sibling of the link that is just clicked ) should be copied to new_list div and then made visible. Here is the code:

$("a.list").each(function() {
    $(this).click(function() {
      var listToShow = $(this).siblings("ul");
      $("#new_list").html(listToShow);
      $("#old_list").hide();
      $("#new_list").show();
      return fa开发者_如何学Pythonlse;
    });
});

This code works for all the links for the first time, but when i click the same link again an empty list comes up.

What am i missing?

Thanks.


When you use a DOM element or a jQuery selection in html, the elements are removed from where they previously were and moved to the new place in the DOM.

If you want to copy them to the location, you need to use .clone:

var listToShow = $(this).siblings("ul").clone();

Note also that you don't need the each call there: the handler is automatically applied to each element in the selection.

$("a.list").click(function() {
    var listToShow = $(this).siblings("ul").clone();
    $("#new_list").html(listToShow);
    $("#old_list").hide();
    $("#new_list").show();
    return false;
});


Anytime you call a jQuery selector, the actions taken upon it effect all objects the selector returns. Try this. This will bind the function to all current and future <a> anchor tags with the class list without using each();

$('a.list').live('click', function() {
  var listToShow = $(this).siblings("ul");
  $("#new_list").html(listToShow);
  $("#old_list").hide();
  $("#new_list").show();
  return false;
});

Check out these links for some education on the subject

http://api.jquery.com/click/

http://api.jquery.com/bind/

http://api.jquery.com/live/


Try something like this. Hope this helps.

 $('#old_list').delegate('a.list', 'click', function() {
     $(this).siblings('ul.sub').clone().appendTo('#new_list');
 });

Remove .clone() if you want to move it instead of copying it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜