jquery does not select jquery added element

后端 未结 3 863
傲寒
傲寒 2020-12-22 06:38

So I have a jquery function that does something when class \'ajaxsubnote\' is clicked

$(\'.ajaxsubnote\').click(function(){
     //do something....
})
         


        
3条回答
  •  猫巷女王i
    2020-12-22 07:32

    The difference between a bind/click event and a delegated on event is this very important.

    When you use bind or a shortcut such as click, it binds the designated event to all elements matching the specific selector at that time. This selector is a snapshot in time and is not updated when new elements are added.

    When you use event delegation you provide a static parent selector and then your dynamic element selector. Now when you click anywhere within the parent selector, jQuery checks to see if the target matches the parent selector. If the target matches the second selector then the event is triggered. This means that you can add and remove elements to the parent content section that match the criteria for the event triggering without having to bind events every time.

    http://api.jquery.com/on/

    So what you need is something like:

    $(parentElement).on( "click", ".ajaxsubnode", function(){
         //do something....
    });
    

    Where the parentElement is as specific as possible while still being a parent of all possible ajaxsubnode classes.

提交回复
热议问题