Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

javascript - Adding click event via addEventListener to confirm navigation from a hyperlink

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 />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...