开发者

When a li is appended, does it not become a part of the ul "for real"?

开发者 https://www.devze.com 2022-12-29 12:40 出处:网络
I have right now this code: <ul><li class=\"listitem\">text<li></ul> jQuery: $(\'.listitem\').click(function() {

I have right now this code:

<ul><li class="listitem">text<li></ul>

jQuery:

$('.listitem').click(function() {  
  $("开发者_如何学编程#elname").text($(this).text());  
  $('#slists').css('visibility','hidden')  
  $('#elname').css('visibility','visible')  
  $('#elname').css('display','inline-block')  
});

This is supposed to hide a div and it does, but when I append items to the ul (with the class listitem) nothing happens with the appended item, the class it gets is correct, the title, and the value too.

Can this have something to do with the code above being in the document ready function to do?


Use .live() instead, like this:

$('.listitem').live('click', function() {  
  $("#elname").text($(this).text())
              .css({ visibility:'visible', display: 'inline-block' });
  $('#slists').css('visibility','hidden')  
});

.live() listens at the document level for your click to bubble up...and new and old elements bubble this event the same way, so it doesn't care what was added later, where as your .click() handler binds a click to elements that existed at the time the selector was run.

Alternatively, you can give your <ul> an ID or class and use .delegate() like this:

$('#myUL').delegate('.listitem', 'click', function() {  
  $("#elname").text($(this).text())
              .css({ visibility:'visible', display: 'inline-block' });
  $('#slists').css('visibility','hidden')  
});

This results in less bubbling, so just a bit neater on the event side, it captures it at the <ul> instead of all the way up on document.


Click events are set once on all elements in the DOM at the time of setting. Adding a list item won't regenerate these click items.

You'll need to use jQuery's live event functionality to create click events that apply to elements created on-the-fly.

0

精彩评论

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