开发者

How do I remove list items that have been added by append?

开发者 https://www.devze.com 2023-04-01 07:08 出处:网络
I want to be able to append items to an unordered list (wibble) when an item is selected from a larger list (user_checkboxes). If 开发者_运维问答a user clicks on an item in the \'wibble\' list I would

I want to be able to append items to an unordered list (wibble) when an item is selected from a larger list (user_checkboxes). If 开发者_运维问答a user clicks on an item in the 'wibble' list I would like to remove that item from the list.

The problem I am having is that the list items 'a' and 'b' work as I was hoping. i.e if i click on the list item they are removed from the list. Unfortunately any items that are added to the list by append don't behave the same way. i.e They don't get selected and removed from the list.

<ul class = "wibble">
<li>a</li>
<li>b</li>  
</ul>


$(document).ready(function () { 
  $(".user_checkboxes").change(function() {
     if ($(this).attr("checked")) {             
        $('.wibble').append('<li>'+newListItem+'</li>');
     }
  }
  $('.wibble li').click(function() {
     $(this).remove();
  );
}


When you bind the click event handler, the list elements don't exist yet, so jQuery cannot bind any handlers to them.

Use .delegate() [docs] instead:

$('.wibble').delegate('li', 'click', function() {
    $(this).remove();
});

This binds an event handler to .wibble (which does exist) and listens to any click that originates from a descendant li element.


you use live

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

or delegate

http://api.jquery.com/delegate/

i asked the very same question not so long ago

Trigger events not working on ajax loaded html

worth mentioning is that performance wise if not so big though delegate is the way to go.


Basically because the new list items are added after the DOM is loaded, jQuery has no reference of them. Theres a simple fix to your method:

$('.wibble li').live('click', function() { 
 $(this).remove(); 

);


The problem is, you are setting the event handler before the new elements are added.

You could add the event handler again every time you add a new element, but luckily jQuery has a function built in that makes sure events get bound to every element even if they are added dynamically later on.

Simply change this line:

$('.wibble li').click(function() {

To this:

$('.wibble li').live('click',function() {
0

精彩评论

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