jQuery click not working for dynamically created i

2019-01-01 05:58发布

This question already has an answer here:

I have a piece of jQuery that loops through each element in a given div( #container) and does a javascript alert each time a span is clicked. This works fine if the <span>'s are static.

However, if I use a piece of code like:

$(someLink).click(function(){
   $("#container").html( <new html with new spans> )
});

The jQuery code doesn't fire off. Oddly enough though

My question is : Is there a reason my Click events don't work for dynamically created items? I assume I will have to add something into my document ready or heartbeat-script (which is fired every 100 miliseconds) to hook up the events??

8条回答
步步皆殇っ
2楼-- · 2019-01-01 06:17

Use the new jQuery on function in 1.7.1 -

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

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 06:19

Using .click will only attach events to elements that already exist.

You need to use a function which monitors for dynamically created events - in older versions of JQuery this was .live(), but this has been superceded by .on()

查看更多
登录 后发表回答