开发者

Remove tags that created after page load with jQuery

I have small application: http://jsfiddle.net/Bwdf6/4/

But with click on delete, tags that created after page load doesnt remove. Is there a开发者_JAVA百科ny way to remove tags that created after page load?

Thanks in advance


Use live() - Working Demo.

$('.sp').live("click", function() {
        $(this).parent().remove();
    });

As you're creating your elements dynamically, using click() isn't enough - that only assigns a click handler to all the .sp elements that exist at the time click() is called.

live(), on the other hand, is used to:

Attach a handler to the event for all elements which match the current selector, now and in the future.

So any new elements added dynamically with a class of sp will have that handler attached to them.

EDIT: Actually, as a couple of people have pointed out, while live() will do what you need, the most efficient function to use in this instance would be delegate(), which is used to:

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

I won't steal glory by posting a code sample - see @Mark's answer, which should be accepted instead of mine.


You can use .live() or .delegate()

.delegate() would be the best option since the items all share a common parent.

$('#theList').delegate(".sp", "click", function() {
    $(this).parent().remove();
});

Updated fiddle


This is why live() is 'invented'.

Change:

$('.sp').click (function() {

with:

$('.sp').live('click', function() {


You can use .live() instead:

http://jsfiddle.net/Bwdf6/5/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜