简体   繁体   中英

After appending an element the event click is not working on the appended element in jquery

I am appending item by Jquery. But after appending can't bind the event on the appended item. I am appending as follows >>

var item =  '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px;">';
    item += '<input id="txtInScope" type="text" value="'+currentScopeVal+'" class="form-control" readonly="readonly"/>';
    item += '</div>';
    item += '<div id="inScopeActionDiv'+newInputId+'" class="col-md-3"  style="padding-left: 2px;">';
    item += '<button type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>';
    item += '</div>';    
$('#inScopeDiv').append(item);

And after appending this I want to bind a click event on the above remButton class as below >>

$("#inScopeDiv").delegate(".remButton", "click", function(){
    alert('you clicked me again!');
});
$('#inScopeDiv').on('click', '.remButton', function() {
    alert("working");
})
$('.remButton').live('click', function() {
    alert('live');
})

But no result. Can anyone please help me on this please?

将它绑定到一个非动态但始终在 DOM 中的父级上。

$('.remButton').live('click', function() {
    alert('live');
})

jquery method live is not valid anymore:

"As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()."

Source: jquery live

Little explanation about event attachment:

You must realize that a target what you want to add a event, exists BEFORE to call the add event function(in this case with the method on of jQuery).

on another hand, exists with jquery a manner to make work a event attachment without the existence of the element before:

$('html').on('click', '#inScopeDiv .remButton', function () {
  alert('works!');
});

You need to add the listener each time you add an item:

$('#inScopeDiv').append(item)
            .off() //unbind old listeners so no duplicate listeners
            .on('click', '.remButton', function() {
               alert("working");
            });

You could store the appended div in a variable using .appendTo and then you could attach the click event directly to the variable. See it working: JSFiddle

$(".appendDiv").click(function () {
      var item = "<div>I'm a new div!</div>";
      var appended_div = $(item).appendTo(".container");
      appended_div.click(function () {
              alert("Working!");
      });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM