jQuery Cant remove li once added

2020-02-16 03:39发布

When I add in a new <li> into the list, and then I try to remove it, it won't let me remove newly added features from the list?

http://jsfiddle.net/43nWM/

Cheers

7条回答
家丑人穷心不美
2楼-- · 2020-02-16 04:10

You can try.

http://jsfiddle.net/43nWM/1/

    $(function(){
      $('#cblist a').live('click', function(){
        $(this).parent('li').remove();
        return false;
      });
    });
查看更多
淡お忘
3楼-- · 2020-02-16 04:14

The secret here is event delegation. When you call .click(function() {...}) or .on('click', function() {...}) that event handler is only assigned to elements that matched the selector when the code was run. It won't affect elements that are added later.

However, you can use event delegation to assign an event handler to a static element that will contain all of your dynamic elements, which will run the callback function whenever an element matching the dynamic selector triggers that type of event:

$('#cblist').on('click', 'a', function() {
    $(this).parent('li').remove();
    return false;
});

Take a look at the section titled Direct and delegated events in the documentation for the .on() function for more information.

查看更多
贼婆χ
4楼-- · 2020-02-16 04:14
$(function(){
     $('#cblist').on('click','a',function(){
         $(this).parent('li').remove();
         return false;
     });
});

View this jsfiddle

查看更多
混吃等死
5楼-- · 2020-02-16 04:17

you should add this code to for addition on dynamic li tags

$li = $('<li>'+name+'</li>');
$a = $('<a href="">remove</a>');
        $a.click(function(){
          $(this).parent('li').remove();
          return false;      
        });
$li.append($a);

i have also updated the code on jsfiddle

查看更多
beautiful°
6楼-- · 2020-02-16 04:25

Another option is to use the on() function, as shown here: http://jsfiddle.net/43nWM/12/

To be honest, I actually prefer the other two solutions here though.

EDIT: Use on() instead. I originally proposed using live()

查看更多
唯我独甜
7楼-- · 2020-02-16 04:28

You are binding the click event only to current 'remove' links, not future ones. Use event delegation for this, to cover both bases. Change:

  $('#cblist a').click(function(){

to

  $('#cblist').on('click', 'a', function() {
查看更多
登录 后发表回答