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

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

问题描述

我正在编写一些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添加click事件以确认从超链接导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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