Javascript 单击 <a> 链接时如何显示确认对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10462839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:25:25  来源:igfitidea点击:

How to display a confirmation dialog when clicking an <a> link?

javascripthtmldom-events

提问by Christoffer

I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.

我希望这个链接有一个 JavaScript 对话框,询问用户“你确定吗?是/否”。

<a href="delete.php?id=22">Link</a>

If the user clicks “Yes”, the link should load, if “No” nothing will happen.

如果用户点击“是”,链接应该加载,如果“否”什么都不会发生。

I know how to do that in forms, using onclickrunning a function that returns trueor false. But how do I do this with an <a>link?

我知道如何在表单中执行此操作,使用onclick运行返回的函数truefalse. 但是我如何使用<a>链接来做到这一点?

回答by kapa

Inline event handler

内联事件处理程序

In the most simple way, you can use the confirm()function in an inline onclickhandler.

以最简单的方式,您可以confirm()在内联onclick处理程序中使用该函数。

<a href="delete.php?id=22" onclick="return confirm('Are you sure?')">Link</a>

Advanced event handling

高级事件处理

But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.

但是通常您希望将HTML 和 Javascript 分开,因此我建议您不要使用内联事件处理程序,而是在您的链接上放置一个类并为其添加一个事件侦听器。

<a href="delete.php?id=22" class="confirmation">Link</a>
...
<script type="text/javascript">
    var elems = document.getElementsByClassName('confirmation');
    var confirmIt = function (e) {
        if (!confirm('Are you sure?')) e.preventDefault();
    };
    for (var i = 0, l = elems.length; i < l; i++) {
        elems[i].addEventListener('click', confirmIt, false);
    }
</script>

This examplewill only work in modern browsers (for older IEs you can use attachEvent(), returnValueand provide an implementation for getElementsByClassName()or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.

此示例仅适用于现代浏览器(对于较旧的 IE,您可以使用attachEvent()returnValue并提供实现getElementsByClassName()或使用类似 jQuery 的库,这将有助于解决跨浏览器问题)。您可以在 MDN 上阅读有关此高级事件处理方法的更多信息。

jQuery

jQuery

I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:

我想远离被认为是 jQuery 狂热分子,但 DOM 操作和事件处理是最有助于解决浏览器差异的两个领域。只是为了好玩,这里是jQuery 的样子:

<a href="delete.php?id=22" class="confirmation">Link</a>
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
    $('.confirmation').on('click', function () {
        return confirm('Are you sure?');
    });
</script>

回答by David says reinstate Monica

I'd suggest avoiding in-line JavaScript:

我建议避免使用内嵌 JavaScript:

var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].onclick = function() {
        var check = confirm("Are you sure you want to leave?");
        if (check == true) {
            return true;
        }
        else {
            return false;
        }
    };
}?

JS Fiddle demo.

JS小提琴演示

The above updated to reduce space, though maintaining clarity/function:

以上更新以减少空间,但保持清晰度/功能:

var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].onclick = function() {
        return confirm("Are you sure you want to leave?");
    };
}

JS Fiddle demo.

JS小提琴演示

A somewhat belated update, to use addEventListener()(as suggested, by ba?megakapa, in the comments below):

一个有点迟到的更新,使用addEventListener()(如ba?megakapa所建议的,在下面的评论中):

function reallySure (event) {
    var message = 'Are you sure about that?';
    action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].addEventListener('click', reallySure);
}

JS Fiddle demo.

JS小提琴演示

The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:

以上为每个单独链接的事件绑定了一个函数;当您可以将事件处理(使用委托)绑定到祖先元素时,这可能非常浪费,例如:

function reallySure (event) {
    var message = 'Are you sure about that?';
    action = confirm(message) ? true : event.preventDefault();
}

function actionToFunction (event) {
    switch (event.target.tagName.toLowerCase()) {
        case 'a' :
            reallySure(event);
            break;
        default:
            break;
    }
}

document.body.addEventListener('click', actionToFunction);

JS Fiddle demo.

JS小提琴演示

Because the event-handling is attached to the bodyelement, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction) to determine what to do with that click. If the clicked element is a link, and therefore has a tagNameof a, the click-handling is passed to the reallySure()function.

因为事件处理附加到body元素上,该元素通常包含许多其他可点击的元素,所以我使用了一个临时函数 ( actionToFunction) 来确定如何处理该点击。如果单击的元素是一个链接,因此具有tagNameof a,则单击处理将传递给该reallySure()函数。

References:

参考:

回答by coder

<a href="delete.php?id=22" onclick = "if (! confirm('Continue?')) { return false; }">Confirm OK, then goto URL (uses onclick())</a>

回答by Wolfack

You can also try this:

你也可以试试这个:

<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
    Link Text
</a>

回答by erik

jAplus

加加

You can do it, without writing JavaScript code

你可以做到,而无需编写 JavaScript 代码

<head>
   <script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
   <script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
   <a href="delete.php?id=22" class="confirm" title="Are you sure?">Link</a>
...
</body>

Demo page

演示页面

回答by Salvioner

Most browsers don't display the custom message passed to confirm().

大多数浏览器不显示传递给confirm().

With this method, you can show a popup with a custom message if your user changed the value of any <input>field.

使用此方法,如果您的用户更改了任何<input>字段的值,您可以显示带有自定义消息的弹出窗口。

You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:

您只能将其应用于页面中的某些链接,甚至其他 HTML 元素。只需向所有需要确认和应用的链接添加一个自定义类,使用以下代码:

$(document).ready(function() {
  let unsaved = false;
  // detect changes in all input fields and set the 'unsaved' flag
  $(":input").change(() => unsaved = true);
  // trigger popup on click
  $('.dangerous-link').click(function() {
    if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {
      return; // user didn't confirm
    }
    // either there are no unsaved changes or the user confirmed
    window.location.href = $(this).data('destination');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="text" placeholder="Nuclear code here" />
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">
    Launch nuke!
</a>

Try changing the input value in the example to get a preview of how it works.

尝试更改示例中的输入值以预览其工作方式。

回答by Chad Killingsworth

This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).

如果您使用 addEventListener(或 attachEvent)附加事件处理程序,则此方法与上述任一答案略有不同。

function myClickHandler(evt) {
  var allowLink = confirm('Continue with link?');
  if (!allowLink) {
    evt.returnValue = false; //for older Internet Explorer
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
}

You can attach this handler with either:

您可以使用以下任一方式附加此处理程序:

document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);

Or for older versions of internet explorer:

或者对于旧版本的 Internet Explorer:

document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);

回答by Florian Margaine

Just for fun, I'm going to use a single event on the whole document instead of adding an event to allthe anchor tags:

只是为了好玩,我将在整个文档上使用单个事件,而不是向所有锚标记添加一个事件:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = evt.target || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );
    }
};

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

如果你有很多锚标签,这种方法会更有效。当然,当您将此事件添加到具有所有锚标记的容器时,它会变得更加高效。

回答by Shah Abd Hafiz

USING PHP, HTML AND JAVASCRIPT for prompting

使用 PHP、HTML 和 JAVASCRIPT 进行提示

Just if someone looking for using php, html and javascriptin a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

如果有人想在单个文件中使用php、html 和 javascript,下面的答案对我有用..我附上了用于链接的引导程序图标“垃圾箱”。

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used phpcode in the middle is because i cant use it from the beginning..

我在中间使用php代码的原因是因为我不能从一开始就使用它..

the code below doesnt work for me:-

下面的代码对我不起作用:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

我像在第一个代码中那样修改它然后我按照我需要的方式运行..我希望我可以帮助需要我的案例的人。