开发者

help needed with jquery .remove on loading new content

I have the following code (snippets) in my website:

The CSS:

#something li{
    display:block;
    width:200px;
    height:100px;
    margin:5px;
    border:1px solid #ccc;
    background:#eee;
    padding:5px;
}
.delete{

}

The HTML:

<a class="addnew" href="#">Add new</a>
<ul id="something">
    <li><a class="delete" href="#">Delete</a></li>
    <li><a class="delete" href="#">Delete</a></li>
</ul>

The JavaScript:

jQuery(document).ready(function($) {
    $('.delete').click(function(){
        $(this).parent().remove();
        return false;
    });

    $('.addnew').click(function(){
            $('ul#something').append('<li><a class="delete" href="#">Delete</a></li>');
        return false;
    });
});

I 开发者_Go百科can add a new list item by clicking on add item, but when I try to delete it, I can't. Is there a solution for this?


Working example: http://jsfiddle.net/VgPsR/4/

$('.delete').click(function(){
    ...
});

Binding a event handler like this affects only those elements currently in the DOM. Dynamic elements later will not have this handler. To attach a handler to current and future elements, you want to use jQuery.live.

$('.delete').live('click', function(){
    ...
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜