[英]Why doesn't my jQuery work for elements loaded via ajax?
我有一個jsp頁面,其中包含具有以下元素的表單:
<form class="form-inline" role="form" action="CadsInsertion" method="POST">
<div id="formItems" class="form-group">
<input type="text" id="date" name="date" placeholder="Date"><label class="btn btn-danger" id="_date">-</label>
</div>
<div class="col-lg-6 col-lg-offset-3">
<button id="submit" type="submit" class="btn btn-warning btn-lg">Submit</button>
</div>
</form>
加載頁面時,我使用以下jQuery添加更多從Servlet FormElements
中獲取的元素。
$(document).ready(function() {
$.ajax({
url: "FormElements",
data: {docType: "<%=session.getAttribute("docType")%>"},
success: function(data) {
if(data != null) {
$("#formItems").append(data);
}
}});
});
我在Servlet中所做的基本上是處理來自ajax調用的數據,並相應地編寫一些jsp元素。 為了簡單起見,我將省略Servlet實現,而僅跳到輸出。
執行ajax代碼后,新元素將添加到formItems
分區中:
<input id="Image" type="text" placeholder="Image" name="Image">
<label id="_Image" class="btn btn-danger">-</label>
<br>
<input id="Format" type="text" placeholder="Format" name="Format">
<label id="_Format" class="btn btn-danger">-</label>
<br>
<input id="Type" type="text" placeholder="Type" name="Type">
<label id="_Type" class="btn btn-danger">-</label>
現在我的問題是,我使用以下jQuery從表單中刪除元素:
$("label").click(function(e) {
var item = e.target.id;
item = item.replace("_", "");
$("#" + item).remove();
e.target.remove();
});
但這僅適用於已經在我的頁面中靜態定義的元素,不適用於使用ajax加載的元素。 為什么是這樣?
一旦添加了元素,就需要將處理程序重新綁定到該元素或使用jQuery的on()函數。
您需要將事件委托給頁面內最接近的靜態祖先元素(另請參見“ 了解事件委托 ”)。 這只是意味着,綁定事件處理程序的元素在綁定處理程序時必須已經存在,因此對於動態生成的元素,必須允許事件冒泡並進一步處理。
用這個
// instead of document you can use any parent element selector which is static(does not appended)
$(document).on("click","label",(function(e) {
var item = e.target.id;
item = item.replace("_", "");
$("#" + item).remove();
e.target.remove();
});
使用事件委托
$("#formItems").on('click', 'label', function(e) {
var item = e.target.id;
item = item.replace("_", "");
$("#" + item).remove();
e.target.remove();
});
$(".form-inline").on('click', 'label', function(e) {
var item = e.target.id;
item = item.replace("_", "");
$("#" + item).remove();
e.target.remove();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.