Removing a dynamically created li from ul

前端 未结 4 1066
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 05:31

I\'m using jquery to add and remove bullets on the fly after the DOM is loaded.

Here\'s the code to add a bullet which works fine:

// add bullet
$(\'         


        
相关标签:
4条回答
  • 2021-01-07 05:43

    Replace the following:

    $('#linkedEventList ul').append('<li id=' + datum._id + '>' + datum.headline + ' <a href=javascript:; title=delete onclick=remove(this) class=itemDelete>(x)</a> <a href=/events/' + datum._id + '>(open)</a></li>');
    

    with this:

    $('#linkedEventList ul').append('<li id=' + datum._id + '>' + datum.headline + ' <a href=javascript:; title=delete class=itemDelete>(x)</a> <a href=/events/' + datum._id + '>(open)</a></li>');
    
    $('#'+datum._id).bind({
       click: function(o) {
          $(this).remove();
       }
    });
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-07 05:44

    Don't you mean

    $(this).parent().remove();
    

    Also, you might want to consider

    $(this).closest('li').remove();
    

    That will go up the DOMtree until it finds a li, if you ever wrap your anchor in another element, the last example wont brake :)

    0 讨论(0)
  • 2021-01-07 05:58

    You could do it using the index of the clicked <li>

    $('li').on('click', function() {
        $(this).parent().children('li:eq(' + $(this).index() + ')').remove();
    });
    

    Edit: this works as well:

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

    See fiddle.

    0 讨论(0)
  • 2021-01-07 06:03

    I used a combination of the answers provided.

    I removed the onclick in the li, and instead referenced the class being clicked and combined that with 'this' as per below.

    $('#linkedEventList').on('click', '.itemDelete', function(){
    $(this).parent().remove();
    });
    

    Here's the jsfiddle that works in both FireFox and Chrome: http://jsfiddle.net/jjgelinas77/CsAJn/27/

    0 讨论(0)
提交回复
热议问题