开发者

(Adding and) Removing list items with JavaScript / jQuery

I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).

Here is the thing. I have a list with lots of stuff in each list item:

<ul id="fruit_list">
    <li>
         <h4> Fruit 1: <a href="#" class="remove">remove</a> </h4>
         <p> blablabla </p>
    </li>

    <li>
         <h4> Fruit 2: <a href="#" class="remove">remove</a> </h4>
         <p> blablabla </p>
    </li>
</ul>

<a href="#" class="add">add</a>

What I want to do, is when I click on the anchor 'remove', to remove the list item containing it.

(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)

So here is what I've written so far:

$(function(){
    var i = $('#fruit_list li').size() + 1;

    $('a.add').click(function() {
        $('<li><h4>Fruit '+i+开发者_如何学Go':<a href="#" class="remove">
             remove</a></h4><p>Blabla</p></li>')
        .appendTo('#fruit_list');
        i++;
    });

    $('a.remove').click(function(){

        $(this).parentNode.parentNode.remove();
        /* The above obviously does not work.. */
        i--;
    });
});

The 'add' anchor works as expected. The 'remove' drinks a lemonade..

So, any ideas? Thanks

EDIT: Thanks for your answers everybody! I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:

$('a.remove').live('click', function(){
    $(this).closest('li').remove();
    i--;
});

Thank you for your rapid help!


The a.remove event binding needs to be a live http://api.jquery.com/live/ binding. The nodes are added to the DOM after doc ready is called.

Additionally, I think you want to use parent() instead of parentNode. Unless I'm behind on my jQuery, parentNode is just DOM manipulation and there's no standard remove(), it's removeChild(). Here you need a jQuery collection returned from parent().


Try $(this).parents("LI").remove();


The reason is that $('a.remove') is only executed once, and so only found at the moment you don't have any remove links yet. To solve this rewrite your ADD function like this:

$('a.add').click(function() {
    var $li = $('<li><h4>Fruit '+i+':<a href="#" class="remove">
         remove</a></h4><p>Blabla</p></li>');
    $li.appendTo('#fruit_list');
    $li.find('a.remove').click(function() {
        $li.remove();
        i--;
    });
    i++;
});

And just remove your old remove function.

EDIT: Oh, this will only work for items you add, if you already load some list items in the html before any Javascript is executed add this function under the $('a.add').click:

$('a.remove').click(function(){
    $(this).parent().parent().remove();
    i--;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜