开发者

Ajax loads new button, do I need to load a new selector?

Let's say that I'm coding a message system for example. Users can add messages开发者_StackOverflow (via AJAX) and next to their messages they've got some buttons. (Edit, Remove, ...)

By loading the page, a few messages are loaded.

<div class="message">
    <p>blaat</p>
    <a href="#" class="btnRemove">Remove</a>
</div>
<div class="message">
    <p>blaat</p>
    <a href="#" class="btnRemove">Remove</a>
</div>

The jQuery selector knows these elements. Because they already exist when I execute the jQuery script. (document.ready) But when I add another "message", jQuery can't handle the 'remove' link because it's loaded after running the jQuery script.

Can somebody help me out? Thanks in advance!


You can use the live method instead of bind (or the shorthand click). So it'd look like:

$('.btnRemove').live('click', function(e) { ... });

This uses event delegation, with the click event handler attached to document rather than any particular element.


You can use jQuery Live method to work on remove which is loaded using ajax.


can you post the JavaScript code with this example? off the top of my head I know the $().live function in jQuery would probably be a good fit for your needs as it will handle the buttons when they are added to the DOM... For example:

$('.btnRemove').live('click', function(e) { ... });

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜