Execute .on() function automatically after page load

后端 未结 2 1160
故里飘歌
故里飘歌 2021-01-29 09:55

I use $(\"#container\").on(\"click\", contentEffects); to make some jquery code work again after ajax call. However, I hope the .on() function can be e

相关标签:
2条回答
  • 2021-01-29 10:37

    use this code to execute .on function after page load.

    $(document).ready(function() {
             $("#container").on("click", function() {
             //Your Code
             });
    });
    
    0 讨论(0)
  • 2021-01-29 10:42

    You can run it in your chain:

    // Anonymouse function passed into $ will be invoked
    // When the document has loaded
    $(function () {
    
        // Immediately after binding the click handler
        // We invoke the click event on #container
        $("#container").on("click", contentEffects).click();
    
    });
    

    What is sounds like you should consider though is event-delegation, and binding events to the nearest static ancestor element that is present when the page loads. For instance, suppose we have a list of items populated dynamically by AJAX:

    <ul id="items">
        <li>First item on load.</li>
        <!-- More items will be loaded
             via AJAX later on --->
    </ul>
    

    You might want the list items to do something when you click on them, so you would probably bind handler to their click event:

    $("#items li").on("click", function () {
        alert( $(this).html() );
    });
    

    This works for any list items already on the page, but as you are experiencing, new items won't have this bound to them, so after your AJAX you will have to re-bind it to all new list items.

    Instead of doing this, we can bind to the ul element, which is always present, and simply listen for events that originated from li elements:

    $("#items").on("click", "li", function () {
        alert( $(this).html() );
    });
    

    Now our event never needs to be re-bound, since #items is loaded with the page, and never goes anywhere. Any click event that bubbles up to this element from a nested list item (whether it was loaded via AJAX or not) will be captured and handled.

    0 讨论(0)
提交回复
热议问题