了解javascript中的事件冒泡

时间:2011-08-11 10:01:52

标签: javascript javascript-events event-bubbling

我一直试图理解甚至冒泡,并且不太确定我完全遵循它。我开始阅读它,以便当用户开始将数据输入表单时(例如,与StackOverflow类似的方式执行!)时,我可以警告用户他们在我的网站上留下页面。

以下代码似乎可以跨浏览器工作:

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&amp;&amp;&lt; submitted == false)到主代码;但是,这个(以及仅在未单击提交按钮时尝试触发页面的所有其他组合)不起作用,当我单击提交按钮时仍然显示警告,或者在没有显示警告时显示警告点击任何东西!

这可能归结为我不理解事件冒泡过程的事实 - 我不知道为什么我需要e.cancelBubble = true;在我拥有它的地方。

所以,我的两个主要问题是:

  • 如何检查是否单击了提交按钮,如果未单击则显示警告
  • 并了解eventBubbling;例如:如果enteredData为true,那么我不会影响冒泡过程。我可以做?如果enteredData为false,e.cancelBubble = false,如果enteredData为true,则e.cancelBubble = true吗?关闭页面时,设置e.cancelBubble的值实际上有什么影响?

我还认为我不需要事件e.stopPropagation 因为firefox支持事件冒泡?

长篇大论道歉,并提前感谢任何人能给予的任何帮助。

谢谢, 克里斯

4 个答案:

答案 0 :(得分:3)

为了理解JS中的事件冒泡,我建议您使用Quirks模式事件简介。

查看http://www.quirksmode.org/js/events_order.html(以及有关该网站内事件的所有链接和部分)

答案 1 :(得分:0)

拥有这样的代码怎么样?

$('#submit').click(function() {
    entereddata = false;
});

这应该在实际表单提交之前调用,即在confirmLeave运行之前调用,因此降低标志应该可以解决问题。

答案 2 :(得分:0)

尝试删除onbeforeunload“listener”:

$('#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是一个不会传播的全局事件。

答案 3 :(得分: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;
    });
}