【发布时间】:2018-08-21 07:33:47
【问题描述】:
我想在由 ajax 调用动态创建的元素上绑定一个事件。 一些元素已经存在,并且在页面加载时与它们绑定了一个事件。但是当在 ajax 调用之后创建新元素时,新元素会失去它们的绑定。
我搜索并找到了一个非常好的解决方案。 Jquery Event won't fire after ajax call
在这个问题中,“Jason Fingar”提出了两种解决方案来解决这个问题
- 第二种解决方案是使用 on 方法,但它对我不起作用
- 第一种方法可行,但存在一些问题
这是他提出的第一个解决方案
"1) 封装您的“绑定”代码,并在页面加载时以及相关元素添加回页面后立即调用它。例如:"
$(document).ready(function(){
// bind event handlers when the page loads.
bindButtonClick();
});
function bindButtonClick(){
$('.myClickableElement').click(function(){
... event handler code ...
});
}
function updateContent(){
$.ajax({
url : '/ajax-endpoint.php',
data : {'onMyWay' : 'toServer'},
dataType : 'html',
type : 'post',
success : function(responseHtml){
// .myClickableElement is replaced with new (unbound) html
element(s)
$('#container').html(responseHtml);
// re-bind event handlers to '.myClickableElement'
bindButtonClick();
}
});
}
我面临什么问题? 该事件与新元素绑定成功,但对于旧元素或页面加载时加载的元素,事件被绑定两次。 这有什么问题?
【问题讨论】:
标签: javascript jquery ajax jquery-events