jquery functions dont work on dom elements loaded

2019-02-27 18:31发布

I wrote jQuery event handlers on DOM elements that are not yet in the page but might be loaded asynchronously into the page. What I observed was these event handlers seem to not recognize that some new elements were added to the DOM and that they need to act on them on triggering.

Am I right in my observation? How do I achieve this functionality?

2条回答
贼婆χ
2楼-- · 2019-02-27 19:11

If you want event handlers to work on dynamically added content, you need to use on

$(document).on("click", "someCssSelector", function(){
    //your code here
});

Of course this will cause all clicks anywhere on your page to be watched. To be more efficient, see if you can structure your page so that all of these elements whose click event you want to handle will be in one container. ie, if all of these elements are going to be added to a div with an id of foo, you'd write the above more efficiently as

$("#foo").on("click", "someCssSelector", function(){
    //your code here
});

If you're using jQuery < 1.7, you'd use delegate

$(document).delegate("someCssSelector", "click", function(){
    //your code here
});
查看更多
Emotional °昔
3楼-- · 2019-02-27 19:36

Am I right in my observation?

Yes.

How do I achieve this functionality?

Using the .on function to subscribe to those event handlers if you are using jQuery 1.7+:

$(document).on('click', '.someSelector', function() {
    ...
});

or using the .delegate function if you are using an older version (higher than 1.4.3):

$(document).delegate('.someSelector', 'click', function() {
    ...
});

For both you could use a more specific root than document to improve performance if you know that those elements will be added to some container for example.

And if you are using some prehistoric version you could go with .live():

$('.someSelector').live('click', function() {
    ...
});
查看更多
登录 后发表回答