onLoad of new element, delegate/on?

前端 未结 2 1382
盖世英雄少女心
盖世英雄少女心 2020-12-18 03:01

Im trying to run a function on an element (.this_button) that is being loaded dynamically. Im using the following code:

$(function(){
    $(\"b         


        
相关标签:
2条回答
  • 2020-12-18 04:01

    The on method will handle events for the currently selected elements when it is first executed or any future elements that raise a particular event that match a specific selector. Since an element being added to a page does not automatically raise a load or some other type of event, your code will never be executed for your newly added elements.

    You have two options. The first is to trigger a custom event whenever your new element is being inserted. For instance,

    $.get("/newElemnet", function(newElement) {
       $('#placeToInsertElement').append(newElement);
       $(newElement).trigger('newElementAdded');
    });
    

    Then your original function would listen for that custom event:

    $(function(){
        $("body").on("newElementAdded", ".this_button", function() {
             console.log("its been loaded");
        });
    }); 
    

    The second option is to constantly poll for the new elements as described in this question.

    0 讨论(0)
  • 2020-12-18 04:03

    From the documentation:

    "In all browsers, the load, scroll, and error events (e.g., on an element) do not bubble. [...] Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event."

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