[英]After appending an element the event click is not working on the appended element in jquery
我正在通過 Jquery 附加項目。 但是在附加后不能在附加項上綁定事件。 我附加如下>>
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);
在附加這個之后,我想在上面的 remButton 類上綁定一個點擊事件,如下所示 >>
$("#inScopeDiv").delegate(".remButton", "click", function(){
alert('you clicked me again!');
});
$('#inScopeDiv').on('click', '.remButton', function() {
alert("working");
})
$('.remButton').live('click', function() {
alert('live');
})
但沒有結果。 任何人都可以請幫助我嗎?
將它綁定到一個非動態但始終在 DOM 中的父級上。
$('.remButton').live('click', function() {
alert('live');
})
jquery 方法 live 不再有效:
“從 jQuery 1.7 開始,.live() 方法已被棄用。使用 .on() 附加事件處理程序。舊版本的 jQuery 用戶應優先使用 .delegate() 而不是 .live()。”
來源: jquery live
關於事件附件的小說明:
您必須意識到要添加事件的目標在調用添加事件函數之前存在(在這種情況下使用 jQuery 的方法)。
另一方面,與 jquery 一起存在的方式是使工作成為事件附件,而之前不存在元素:
$('html').on('click', '#inScopeDiv .remButton', function () {
alert('works!');
});
每次添加項目時都需要添加偵聽器:
$('#inScopeDiv').append(item)
.off() //unbind old listeners so no duplicate listeners
.on('click', '.remButton', function() {
alert("working");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.