how to make live click event on new added DOM

本秂侑毒 提交于 2019-11-30 09:46:58

问题


i am a live() user and i know somehow live() is deprecated. i've tried to use bind() to have the event on new added dom working, but it's not.

can you please tell me how to do bind() properly ? or is there any other method to do this task?

this is the html:

<table>
    <tr>
        <td> hi there <span class="click">click me</span></td>
    <tr>
    <tr>
        <td> hi there2 <span class="click">click me</span></td>
    <tr>
    <tr class="end">
        <td></td>
    </tr>
</table>
<button class="add_new">add new row</button>  

this is the js :

var new_row = '<tr><td> hi there, new row! <span class="click">click me</span></td><tr>';

$('.add_new').click(function() {
    $('.end').before(new_row);    
});


$('.click').bind('click', function() {
   alert('clicked');
});

if possible, i want to use native jquery's method and not plugins. this is my jsfiddle http://jsfiddle.net/bondythegreat/z3uXH/


回答1:


You need to use the dynamic version of jQuery's .on() or .delegate().

$('table').on('click', '.click', function() {
    // your code here
});

For dynamic behavior using delegated event handling, the basic idea is that the first select (in the jQuery object) must be a static parent object that is not dynamically created after the event handler is installed. The second selector which is passed as the second argument to .on() is a selector that matches the specific item you want the event handler on. These items can be dynamically created after the event handler is installed.

Using .click() or .bind() gets you static event handlers that only work on objects that are present at the time the code is initially run.

To make this code more robust, I'd suggest two things. First, don't use a class name like "click" that is very easy to confuse with an event. Second, put an id on your table, so that ID can be referenced in the first selector rather than the very generic "table" that may accidentally be active on other tables in your page.




回答2:


You need to use jQuery's on() method

Like so:

$('table').on('click', '.click', function() {
   alert('clicked');
});




回答3:


As of jQuery 1.7+ live() is replaced by on(). The doc pages for live() have a guide how to update to newer methods.

In your case that would translate to:

$('table').on('click','.click', function() {
   alert('clicked');
});

See an altered & working fiddle



来源:https://stackoverflow.com/questions/10084293/how-to-make-live-click-event-on-new-added-dom

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