Dynamically Inserted DOM Elements are not Clickable using $.click()

左心房为你撑大大i 提交于 2019-12-24 07:45:44

问题


I'm using jQuery to take the value of a form element and place it inside a list item tag. There is a maximum value of three list items (these are to become tags for an image).

The problem is that i want people to be able to remove any erroneous tags they've entered by clicking on them, but the items (which are dynamically inserted into a <ul> tag using jQuery) are not clickable using:

$('li.tag').click(function(){ /* Do stuff here */ });

it won't even fire off an alert.

Does anyone have any ideas how i can work around this problem?


回答1:


I think you're looking for the live method: http://api.jquery.com/live/

Perhaps you could do something like

$('li.tag').live('click', function() { /* Do stuff here */ });



回答2:


Use live or liveQuery plugin.




回答3:


As @vmassuchetto mentions, since jQuery 1.7 .live() has been deprecated & removed completely in 1.9. Now you should use .on(). Like so:

$('li').on('click', '.tag', function() {
    ...
});

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

"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers."



来源:https://stackoverflow.com/questions/2412691/dynamically-inserted-dom-elements-are-not-clickable-using-click

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