how to make live click event on new added DOM

蓝咒 提交于 2019-11-29 16:41:26

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.

You need to use jQuery's on() method

Like so:

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

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

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