开发者

Binding events to not yet created DOM elements (jquery)

开发者 https://www.devze.com 2023-01-10 03:17 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消