Appending HTML w/click event using jQuery

前端 未结 4 2127
小蘑菇
小蘑菇 2021-02-20 15:59

I want to append some HTML inside this div, and the HTML has to have a click event on it also.

    

hello, world!

4条回答
  •  无人及你
    2021-02-20 16:32

    IMPORTANT:

    Take into account that the performance should be better if you use the most specific selector. For this case, if you want only affect the divs inside the "MyId" div, you should use:

    $("#MyId").on("click", "div", function(e) {
        // Whatever you want to do when the divs inside #MyId div are clicked
    });
    

    VERY IMPORTANT:

    Take into account that the second parameter for the on method, in this case "div", is optional, but you NEED to provide it if you want the event to be automatically attached to the dinamically created items. This is called deferred in the jquery documentation for "on" method. I hope this info saves time for someone reading this in the future :)

提交回复
热议问题