jQuery $(this).remove() 在追加后不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9665646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:07:27  来源:igfitidea点击:

jQuery $(this).remove() not working after append

jqueryappend

提问by svenkapudija

I have a div with class="tags"with one predefined hyperlink.

我有一个class="tags"带有一个预定义超链接的 div 。

<div class="tags">
     <a href="#">myLink</a>
</div>

And I have function to remove that hyperlink if user clicks on it.

如果用户点击它,我有删除该超链接的功能。

$('.tags a').click(function() {
    $(this).remove();
    return false;
});

And this works with predefined hyperlinks. If I add another links with the help of jQuery (after the page is loaded)

这适用于预定义的超链接。如果我在 jQuery 的帮助下添加另一个链接(页面加载后)

$('.tags').append('<a href="#">newLink</a>');

Function to remove hyperlink (on click) won't be called on these, added links. How to solve this?

不会在这些添加的链接上调用删除超链接(点击时)的功能。如何解决这个问题?

采纳答案by kufi

You have to use the live-function:

您必须使用实时功能:

$(".tags a").live("click", function() {
    // ...
});

Because you are adding the links after the initial load, the standard click event won't be binded to the dynamic added links.

因为您是在初始加载后添加链接,所以标准点击事件不会绑定到动态添加的链接。

回答by sandeep

Your click event only attached to current dom element not to future element.If you want to add this event to all element include future then you have to use live event in jquery. http://jsfiddle.net/6cGvt/

您的点击事件仅附加到当前 dom 元素,而不附加到未来元素。如果您想将此事件添加到所有包含未来的元素,那么您必须在 jquery 中使用实时事件。 http://jsfiddle.net/6cGvt/