Execute .on() function automatically after page load

后端 未结 2 1161
故里飘歌
故里飘歌 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: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:

    • First item on load.

    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.

提交回复
热议问题