Understanding event bubbling in javascript

橙三吉。 提交于 2019-12-05 10:21:44

For understanding event bubbling in JS, I recommend you the Quirks Mode Introduction to Events.

Check out http://www.quirksmode.org/js/events_order.html (also all links and sections regarding events inside that site)

What about having such code?

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

This should be called before the actual form submission i.e. before confirmLeave is running, so lowering the flag should do the trick.

Uoli

Try removing the onbeforeunload "listener":

$('#submit').click(function() {
    window.onbeforeunload=null;
});

I don't think you need to worry about bubbling in this example...

return null if you want the browser to move on without asking the user, or return a string if you want the browser to show an alert asking the user if he wants to move on or not...

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;
    }
}

Bubbling and propagation only applies to event's that should notify it's children or it's parents, and as far as i know window.onbeforeunload is a global event that will not be propagated.

Unrelated to bubbling, but you could bypass detecting whether keys were pressed and check the form data instead:

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;
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!