简体   繁体   中英

Why does return false not work with AddEventListener and what is Javascript's replacement for preventDefault()?

I have the following code which is not working

var Settings = {
    addConfirmations: function() {
        var e = document.querySelectorAll(".bg-red");
        for (var t = 0; t < e.length; t++) {
            e[t].addEventListener("click", function() {
                var e = this.getAttribute("title");
                return Settings.confirmation(e)
            })
        }
    },
    confirmation: function(e) {
        if (e === null || e.toString().length === 0) {
            e = "Are you sure you want to proceed?"
        }
        return window.confirm(e);
    }
}
window.onload = Settings.addConfirmations();

This code adds a click event to all button with a "bg-red" class, now this does not work because return false does not cancel an event if added using AddEventListener , I was advised to use event.preventDefault() instead but this is not an option as I don't use jQuery. I only use pure javascript.

So, why does return false not work with AddEventListener and is there a pure javascript replacement for event.preventDefault(); ?

event.preventDefault() is a part of standard javascript.

jQuery has it's own override version too for compatibility with old IE browsers that did it a different way, but in modern browsers you can use it directly in plain javascript.

So event.preventDefault() is the preferred way of cancelling the default behavior from an event handler added with .addEventListener() .

MDN documentation for event.preventDefault()

W3C specification for event.preventDefault()


return false is simply not a feature of addEventListener() . It works from event handlers specified in the HTML with attributes like onclick=... , but not for event handlers added using addEventListener() . I can't speak to why the original designers made this choice, but that is the way it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM