jQuery .click()不会在使用.wrapInner()动态创建的链接上触发

时间:2022-02-20 20:16:41

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:

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

The HTML:

HTML:

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

The jQuery:

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>');
});

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.

“测试”链接正常工作,因为它应该是第一次被点击 - 它被转换为纯文本)。为了不在这里粘贴大部分脚本,我创建了一个临时函数,它将包装div的内容,将“test”纯文本转换回链接。这就是它变得混乱的地方 - 第一个函数的.click()监听器将不再在这个动态创建的链接上触发,而FireBug不会抛出任何错误或警告。

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

你也可以在JSfiddle上看到这个:http://jsfiddle.net/rWz69/

Any help on this would be more than appreciated !

任何有关这方面的帮助都将不胜感激!

1 个解决方案

#1


11  

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

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

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

Here's your fiddle example updated/working with the above code :)

这是你的小提琴示例更新/使用上面的代码:)

#1


11  

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

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

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

Here's your fiddle example updated/working with the above code :)

这是你的小提琴示例更新/使用上面的代码:)