Adding click event via addEventListener to confirm

2020-02-19 10:47发布

I am writing some JavaScript that what I essentially want to do is confirm when a user clicks a link that they do actually want to click it.

My code currently looks like this:

var Anchors = document.getElementsByTagName("a");

for (var i = 0; i < Anchors.length ; i++)
{
    Anchors[i].addEventListener("click", function () { return confirm('Are you sure?'); }, false);
}

This code displays the confirm box as I would expect to see it, but then navigates to the link regardless of the button pressed in the confirm box.

I believe the problem is related to my usage of the addEventListener (or a limitation of the implementation of it) because if I add manually write the following in a HTML file, the behaviour is exactly what I would expect:

<a href="http://www.google.com" onclick="return confirm('Are you sure?')">Google</a><br />

3条回答
神经病院院长
2楼-- · 2020-02-19 11:31

You have to prevent the execution of the default event handler.

See How to use Javascript's addEventListener() to override an HTML Form's default submit() behavior

--EDIT--

We'll, I've seen you've answered yourself while I was editing the answer

查看更多
疯言疯语
3楼-- · 2020-02-19 11:33

I changed your onclick function to include a call to event.preventDefault() and it seemed to get it working:

var Anchors = document.getElementsByTagName("a");

for (var i = 0; i < Anchors.length ; i++) {
    Anchors[i].addEventListener("click", 
        function (event) {
            event.preventDefault();
            if (confirm('Are you sure?')) {
                window.location = this.href;
            }
        }, 
        false);
}

(See http://jsfiddle.net/ianoxley/vUP3G/1/)

查看更多
▲ chillily
4楼-- · 2020-02-19 11:35

Solution pulled from Original Poster question

After some more searching I have found the answer here on Stack Overflow: Returning false from click handler doesn't work in Firefox

In case anyone finds this question instead of the other, basically when using the addEventListener method of wiring events, you cant just use return false; to cancel the action, you must instead use the preventDefault() method of the event, so my code from above has now become:

Anchors[i].addEventListener("click", function (event) { 
    if (!confirm('Are you sure?')) { event.preventDefault(); } 
}, false);
查看更多
登录 后发表回答