通过 addEventListener 添加点击事件以确认从超链接导航 [英] Adding click event via addEventListener to confirm navigation from a hyperlink

查看:16
本文介绍了通过 addEventListener 添加点击事件以确认从超链接导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些 JavaScript,我本质上想要做的是确认用户单击链接时他们确实想要单击它.

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.

我认为问题与我对 addEventListener 的使用有关(或它的实现限制),因为如果我在 HTML 文件中手动添加编写以下内容,则行为正是我希望:

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

推荐答案

我更改了您的 onclick 函数以包含对 event.preventDefault() 的调用,它似乎让它工作:

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

(参见 http://jsfiddle.net/ianoxley/vUP3G/1/)

这篇关于通过 addEventListener 添加点击事件以确认从超链接导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆