jQuery .click() not triggering on links dynamically created with .wrapInner()

六月ゝ 毕业季﹏ 提交于 2019-12-08 07:22:54

问题


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:

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

The 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.

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

Any help on this would be more than appreciated !


回答1:


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

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

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



来源:https://stackoverflow.com/questions/3681425/jquery-click-not-triggering-on-links-dynamically-created-with-wrapinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!