Binding events to not yet created DOM elements (jquery)
How do I bind events to html elements that don't exist at the time of the script loading?
One part of my script adds these to the DOM:
<a class="btn-remove-item" href="">link</a>
The problem is I can't just do:
$(document).ready(function(){
$(".btn-remove-item").click(function(){
this.parentNode.removeChild(this);
});
});
.. I think because the DOM element isn't there when the page firs开发者_如何转开发t loads.
How should I bind the event to myClass?
jQuery.live() has been deprecated. Here is the accepted answer using jQuery.on() instead:
$(document).on('click', '#btn-remove-item', function() {
this.parentNode.removeChild(this);
});
The jQuery live() function does this:
$("#btn-remove-item").live('click', function() {
this.parentNode.removeChild(this);
});
jQuery.live() is what you need.
$(document).ready(function(){
$("a.myClass").live('click', function() {
this.parentNode.removeChild(this);
});
});
Try it out: http://jsfiddle.net/mwR8g/
$(document).ready(function(){
$(".btn-remove-item").live('click', function() {
this.parentNode.removeChild(this);
});
});
You are need to use live.
精彩评论