开发者

jQuery: Add an index number to a cloned list element

开发者 https://www.devze.com 2023-03-05 19:34 出处:网络
this is almost right, it is not a very complicated question... I have a <ul> that I can add and delete <li>\'s from.

this is almost right, it is not a very complicated question...

I have a <ul> that I can add and delete <li>'s from.

Working example is here.

http://jsfiddle.net/6ELzf/1/

When I add or delete a <li>, I would like to reset the span.number's...

So if I have 3 list items:

<ul>
  <li><span class="number">1</span></li>
  <li><span class="number">2</span></li>
  <li><span class="number">3</span></li>
</ul>

And I delete th开发者_JS百科e first one, I would like it to display:

<ul>
  <li><span class="number">1</span></li>
  <li><span class="number">2</span></li>
</ul>

Not:

<ul>
<li><span class="number">2</span></li>
<li><span class="number">3</span></li>
</ul>

Any thoughts on how to update this...

function index_list() {
  $("#thelist > li").each(function(i){
      $(this).find(".number").html((i + 1));
    });
}


The problem is you're not deleting the <li>, just hiding it

THIS is probably what you want.

I changed this:

$(fadeit).fadeOut();
index_list();

to this:

$(fadeit).fadeOut(function() {
    $(this).remove();
    index_list();
});


Updated your code @ http://jsfiddle.net/6ELzf/2/

Your hiding the li your index_list() can still find it when it does its reindexing..

function index_list() {
 $("#thelist > li").each(function(i){
     $(this).find(".number").html((i + 1));
   });
}

var batch = $("li.foo").clone();


$("#add").live('click', function(e) {
  e.preventDefault();     
   $('#thelist').append(batch.clone());
  index_list();
});

$('.remove').live('click', function() {
   var fadeit = $(this).parents('.foo');
   $(fadeit).fadeOut(400, function() {
      $(this).remove();
      index_list();
   });
 });
0

精彩评论

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