我有下面的代码在窗口卸载会话无效
window.onbeforeunload = function(event) {
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
console.log("closing the browser, invalidating the session");
$.ajax({
url : "/inValidateOnBrowserClose.html",
type : "get",
cache : false,
}).done(function(data) {
console.log(" invalidated session on browser close event");
});
}
return true;
};
$(function() {
$("a").click(function() {
window.onbeforeunload = null;
});
$("button").click(function() {
window.onbeforeunload = null;
});
});
所有工作正常,但我有一个页面,我有一个动态创建的按钮。
<span class="myButton"><a href="javascript:submitForm" >Update </a></span>
当我点击上方的锚(按钮)我的窗口卸载事件被调用(在我的情况下,它不应该被调用),我很惊讶为什么$("a").click(function())
不被称为第一,我试图解决这个问题,但没有运气。谢谢你的回答
您需要像下面这样使用delegate
来将点击事件绑定到动态生成的元素:
$(function() {
$(document).delegate("a","click",function() {
window.onbeforeunload = null;
});
$(document).delegate("button","click",function() {
window.onbeforeunload = null;
});
});
这适用于已经存在的元素,所以不需要编写单独的点击绑定。
对于firefox用户delegate
功能可能不工作,所以他们可以使用on
。请参阅下面的代码
$(function() {
$("a").on("click",function() {
window.onbeforeunload = null;
});
$("button").on("click",function() {
window.onbeforeunload = null;
});
});
Stackoverflow问题