Click event doesn't work on dynamically generated elements
This question already has an answer here:
The click()
binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on()
.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
Source
Here's what you're looking for:
var counter = 0;
$("button").click(function() {
$("h2").append("<p class='test'>click me " + (++counter) + "</p>")
});
// With on():
$("h2").on("click", "p.test", function(){
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2>
<button>generate new element</button>
Use the .on()
method with delegated events
$('#staticParent').on('click', '.dynamicElement', function() {
// Do something on an existent or future .dynamicElement
});
The .on()
method allows you to delegate any desired event handler to:
current elements or future elements added to the DOM at a later time.
PS: Don't use .live()
! From jQuery 1.7+ the .live()
method is deprecated.
Reason:
In jQuery, Click()- attaches the event handler only if the element already exist in the html code.
It won't consider the new element which is created dynamically(Future element) after the page loaded.
Dynamic elements are created with the help of javascript or jquery(not in html) .
So the click event doesn't fire.
Solution :
To overcome this we should use on() function.
delegate(),live() and on() functions have the advantages over the DOM elements.
on can trigger both existing elements as well as future elements.
on can consider the elements which are all present in the whole page.
delegate(),live() functions are deprecated(Don't use these).
You should use on function to trigger the event on dynamically created (future) elements.
Remove the code from $(document).ready:
$(".test").click(function(){
alert();
});
Change into:
$(document).on('click','.test',function(){
alert('Clicked');
});
链接地址: http://www.djcxy.com/p/71566.html
上一篇: 用jQuery获取元素类型
下一篇: Click事件不适用于动态生成的元素