jQuery .click()不会在使用.wrapInner()动态创建的链接上触发 [英] jQuery .click() not triggering on links dynamically created with .wrapInner()

查看:141
本文介绍了jQuery .click()不会在使用.wrapInner()动态创建的链接上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个脚本中遇到问题,对于我的生活,我无法弄清楚它有什么问题。快速浏览我所拥有的:

I'm having an issue with this script and for the life of me I can't figure out what's wrong with it. Quick run through what I have:

HTML:

<ul>
    <li id="wildcard_1">
        <div>
            <a href="#">test</a>
        </div>
    </li>
</ul>
<a href="#" class="reset">reset</a>

jQuery:

// Main function
$("[id^=wildcard_]").children('div').children('a').click(function() {
    $(this).replaceWith($(this).text());
});

// Temporary reset function
$("a.reset").click(function() {
    $("[id^=wildcard_]").children('div').wrapInner('<a href="#"></a>');
});

测试链接的工作原理是第一次被点击 - 它是被转换成纯文本)。为了不在这里粘贴大部分脚本,我创建了一个临时函数,它将包含 div 的内容,将测试纯文本转换为链接。这是haywire的地方 - 第一个函数的 .click()监听器将不会在此动态创建的链接上触发,FireBug不会抛出任何错误,警告。

The "test" link works as it's supposed to the first time is is being clicked -- it is being transformed into plain text). In order not to paste the bulk of the script here, I have created a temporary function that will wrap the contents of the div, transforming the "test" plain text back into a link. And this is where it goes haywire -- the .click() listener of the first function will not trigger on this dynamically created link anymore and FireBug isn't throwing any errors nor warnings.

您还可以在JSfiddle上看到这一点: http ://jsfiddle.net/rWz69/

You can also see this live on JSfiddle: http://jsfiddle.net/rWz69/

对此的任何帮助将不胜感激!

Any help on this would be more than appreciated !

推荐答案

您可以使用 .live( ) 处理程序,如下所示:

You can use .live() handler, like this:

$(document).on("click", "[id^=wildcard_] > div > a" , function() {
  $(this).replaceWith($(this).text());
});

这是您的小提琴更新/使用上述代码:)

这篇关于jQuery .click()不会在使用.wrapInner()动态创建的链接上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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