jQuery - Find dynamically created element without events

后端 未结 2 657
借酒劲吻你
借酒劲吻你 2021-01-19 22:15

Tho this question has been asked before, and the answer is this:

$(\'#container\').on(\'click\',\'#dynamicElement\', function(){ /* the code */ });
         


        
2条回答
  •  孤街浪徒
    2021-01-19 22:55

    How event binding works is as long as that element is in the DOM itself, you can access it by

    $('#dynamicElement)
    

    The reason you need event delegation is when you dynamically create the elements after you bound the event. Then, when the event is fired, it looks through all the children of the element you bound it to to find if there are any elements matching your selector.

    However, if you know that the element has already been appended to the DOM, you can bind it directly without event delegation, and access it through finding it by ID.

    If it hasn't yet, there is no way for you to manipulate it as it doesn't exist yet.

提交回复
热议问题