jquery functions dont work on dom elements loaded asynchromously

前端 未结 2 1685
萌比男神i
萌比男神i 2021-01-24 23:58

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 wa

2条回答
  •  梦毁少年i
    2021-01-25 00:16

    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() {
        ...
    });
    

提交回复
热议问题