jQuery $(this).remove() 在追加后不起作用 [英] jQuery $(this).remove() not working after append

查看:31
本文介绍了jQuery $(this).remove() 在追加后不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<a href="#">myLink</a>

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

$('.tags a').click(function() {$(this).remove();返回假;});

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

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

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

解决方案

你必须使用 live-function:

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

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

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

<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)

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

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

解决方案

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.

这篇关于jQuery $(this).remove() 在追加后不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆