最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery function does not work on appended html - Stack Overflow

programmeradmin0浏览0评论

I want to append a div with jQuery and then use jQuery click function on a class which is inside the appended div. Here's my code, it does not work if I append the div, however it works fine if the div already exists in the html.

HTML:

<div class="add">
    Add item
</div>

<div class="container">
</div>

jQuery:

$('.add').click(function(e){
    e.preventDefault();

    var box = '<div class="box"><div class="remove">x</div></div>'
    $('.container').append(box)
});


$('.remove').click(function(){
    alert("remove");
});

Demo:

/

I want to append a div with jQuery and then use jQuery click function on a class which is inside the appended div. Here's my code, it does not work if I append the div, however it works fine if the div already exists in the html.

HTML:

<div class="add">
    Add item
</div>

<div class="container">
</div>

jQuery:

$('.add').click(function(e){
    e.preventDefault();

    var box = '<div class="box"><div class="remove">x</div></div>'
    $('.container').append(box)
});


$('.remove').click(function(){
    alert("remove");
});

Demo:

http://jsfiddle/Y625A/

Share Improve this question asked May 22, 2013 at 12:33 user1251698user1251698 2,14313 gold badges35 silver badges52 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

Use event delegation

$('.container').on('click','.remove',function(){
    alert("remove");
});

Demo --> http://jsfiddle/Y625A/2/

  • http://api.jquery./on/
  • http://learn.jquery./events/event-delegation/

Try using live to bind the events, this will bind them when the new items are created:

$('.add').live('click', function(e){

});

You have to bind the click even once you create the element:

$('.add').click(function(e){
    e.preventDefault();

    var box = "<div class='box'><div class='remove'>x</div></div>"
    $('.container').append(box)

$('.remove').click(function(){
    alert("remove");
});


});

http://jsbin./ofoteq/1/edit

发布评论

评论列表(0)

  1. 暂无评论