我一直试图理解甚至冒泡,但不确定我是否完全遵循它。我开始阅读它,以便在用户开始在表单中输入数据时以警告用户,当他们在我的网站上离开页面时(以类似于Stack Overflow的方式!)。
以下代码似乎可以跨浏览器工作:
var entereddata = false;
$(document).ready(function()
{
$('#contactform').bind('keypress',function(e) {
if((e.which > 96 && e.which < 123) || (e.which > 47 && e.which < 58)) {
entereddata = true;
//alert(e.which);
}
});
});
function confirmLeave(e, d)
{
if(!e) e = window.event;//window.event;
if(!d) d = entereddata;
var confirmationMessage = 'It appears you have started to enter information into the contact form, but have not yet submitted it';
if(!d)
{
e.cancelBubble = true;
} else
{
return confirmationMessage;
}
}
window.onbeforeunload=confirmLeave;
但是,当我单击不需要的表单的提交按钮时,也会调用它。我已经尝试过对代码进行各种添加,例如添加:
if($('#submit').click()){
submitted=true;
} else {
submitted=false;
}
然后将if(!d)
更改为if(!d && submitted==false)
为主要代码;但是,此操作(以及尝试仅在未单击“提交”按钮时才触发页面的所有其他组合)不起作用,当我单击“提交”按钮时仍显示警告,或者在单击时不显示警告点击任何东西!
这可能归结为我不了解事件冒泡过程的事实-我不知道为什么在需要的地方需要e.cancelBubble = true;
。
所以,我的两个主要问题是:
enteredData
为true,那么我不会影响冒泡过程。我可以做?如果e.cancelBubble=false
为假,我应该有enteredData
吗?如果e.cancelBubble=true
为真,我应该有enteredData
吗?关闭页面时,设置e.cancelBubble
的值实际上有什么作用?我是否也认为我不需要此事件e.stopPropagation
完全是因为Firefox支持事件冒泡?
拥有这样的代码怎么办?
$('#submit').click(function() {
entereddata = false;
});
应该在实际提交表单之前,即在运行confirmLeave
之前调用它,因此降低标志应该可以解决问题。
尝试删除onbeforeunload“侦听器”:
$('#submit').click(function() {
window.onbeforeunload=null;
});
我认为您在此示例中无需担心冒泡...
如果想让浏览器不询问用户就继续前进,则返回null;如果要让浏览器显示询问用户是否要继续前进的警告,则返回一个字符串。
function confirmLeave(e) {
e = e || window.event;//window.event;
var confirmationMessage = 'It appears you have started to enter information into the contact form, but have not yet submitted it';
if(entereddata) {
return confirmationMessage;
} else {
return null;
}
}
冒泡和传播仅适用于应该通知其孩子或父母的事件,据我所知window.onbeforeunload是一个不会传播的全局事件。
与冒泡无关,但是您可以绕过检测是否已按下键并改为检查表单数据:
function hasNonemptyTextInputs() {
var textInputs = $('#contactform :input').filter(':text, textarea');
// Check for any field with a nonempty value
// .is() returns true iff the function returns true on any element
return textInputs.is(function() {
return $(this).val().length > 0;
});
}
与冒泡无关,但是您可以绕过检测是否已按下键并改为检查表单数据:
function hasNonemptyTextInputs() {
var textInputs = $('#contactform :input').filter(':text, textarea');
// Check for any field with a nonempty value
// .is() returns true iff the function returns true on any element
return textInputs.is(function() {
return $(this).val().length > 0;
});
}