jquery - 删除使用jQuery加载页面后创建的标签

原文 标签 jquery

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 any way to remove tags that created after page load?

Thanks in advance

Answer

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.

翻译

我有小的应用程序:
http://jsfiddle.net/Bwdf6/4/

但是单击删除后,页面加载后创建的标签不会删除。
有什么方法可以删除页面加载后创建的标签?

提前致谢
最佳答案
使用live()-Working Demo

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


在动态创建元素时,使用click()是不够的-仅将单击处理程序分配给调用.sp时存在的所有click()元素。

另一方面,live()用于:


  将处理程序附加到所有事件
  与当前匹配的元素
  选择器,现在和将来。


因此,使用sp类动态添加的任何新元素都将附加该处理程序。

编辑:实际上,正如一些人指出的那样,尽管live()会做您需要的事,但在此实例中使用的最有效的函数是delegate(),它用于:


  将处理程序附加到一个或多个事件
  对于所有与
  选择器,现在或将来基于
  在一组特定的根元素上。


我不会通过发布代码示例来窃取荣耀-参见@Mark的答案,应该接受它而不是我的。
相关推荐

jquery - 帮助attr,mouseenter和mouseout无法正常运行

javascript - 单击链接时如何在特定的div中添加文本

javascript - 如何在jQuery中延迟ajax调用?

javascript - 使用jQuery从两个值中获取两个值

jquery - 使用jQuery更改li的背景颜色

jquery - 使用jQuery获取边框样式

javascript - jQuery交互式地图库? [关闭]

jquery - 滚动jQuery问题。如何自动滚动onclick到div

javascript - 如果元素在jQuery中具有某个类,如何忽略click()?

php - 使用AJAX发送阵列的最佳策略