jquery click event not firing on dynamically created div

我是研究僧i 提交于 2019-12-02 12:44:17

I think your problem lies with the $(this) before your selector. What does $(this) refer to in the .ready() scope?

Heres your issue.

The reason .on works is because it delegates events to an element that already exists, like the document, body, or some static parent element not inserted after the dom load, and when that element is acted on based on the FIRST paramenter (click, blur, etc), then it will ask to check if the second parameter is a function or a valid selector.

newPlan.on("click",function(){
    .... 
})

should be

$someParentElement.on("click", '.newPlanSelector', function(){
    .... 
})

This is because events can not be bound to non existent element. Ff you bind some events, then add a that element, all events will be nullified. The way to get around this is to bind to a static element.

Since events bubble from the clicked element, upwards through the DOM tree, they hit every node on the way up. This event will have the source elements info (class/id/etc). Now, this is good because we can't nececarrily tell the element that doesn't exist what to do when it's clicked if we're unsure it exists (or even if we try) but we CAN tell a static parent of this object to act when it recieves a certain type of event (click, blur, etc) from a specified target (list item, link, etc).

Event delegation is the official term.

Happy hunting!:)

Update: Also, ensure you don't use ($(this)) as A.A. posted, this is often an issue. Use $.proxy(function() { }) and call REAL values.

this.$someParent is good object naming :) this.someParent is bad object naming :)

Just some random tips. Don't expect an accepted answer outa this one :P

The live event binding has to be set on a selector for it to be attached to click event when a new div is dynamically created. You are doing a $.find(), which would only search within the current element, and attach the click event to the elements that were found. The solution for your issue would be to attach the click event using "$.live()" on a selector.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!