简体   繁体   English

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

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

I want this link to have a JavaScript dialog that asks the user “ Are you sure?我希望这个链接有一个 JavaScript 对话框,询问用户“你确定吗? Y/N ”.是/否”。

<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 onclick running a function that returns true or false .我知道如何在表单中执行此操作,使用onclick运行返回truefalse的函数。 But how do I do this with an <a> link?但是我如何使用<a>链接来做到这一点?

Inline event handler内联事件处理程序

In the most simple way, you can use the confirm() function in an inline onclick handler.以最简单的方式,您可以onclickonclick处理程序中使用confirm()函数。

<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 example will only work in modern browsers (for older IEs you can use attachEvent() , returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues).此示例仅适用于现代浏览器(对于较旧的 IE,您可以使用attachEvent()returnValue并提供getElementsByClassName()的实现或使用像 jQuery 这样的库来帮助解决跨浏览器问题)。 You can read more about this advanced event handling method on MDN .您可以 在 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.我想远离被认为是 jQuery 狂热分子,但 DOM 操作和事件处理是两个最有助于解决浏览器差异的领域。 Just for fun, here is how this would look with jQuery :只是为了好玩,这里是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>

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 body element, which normally contains a host of other, clickable, elements I've used an interim function ( actionToFunction ) to determine what to do with that click.因为事件处理附加到body元素,它通常包含许多其他可点击的元素,所以我使用了一个临时函数 ( actionToFunction ) 来确定如何处理该点击。 If the clicked element is a link, and therefore has a tagName of a , the click-handling is passed to the reallySure() function.如果点击的元素是一个链接,并因此具有tagNamea ,点击装卸传递给reallySure()函数。

References:参考:

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

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演示页面

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

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the 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.当然,当您将此事件添加到具有所有锚标记的容器时,它会变得更加高效。

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.您只能将其应用于页面中的某些链接,甚至其他 HTML 元素。 Just add a custom class to all the links that need confirmation and apply use the following code:只需向所有需要确认和应用的链接添加一个自定义类,使用以下代码:

 $(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.尝试更改示例中的输入值以预览其工作方式。

USING PHP, HTML AND JAVASCRIPT for prompting使用 PHP、HTML 和 JAVASCRIPT 进行提示

Just if someone looking for using php, html and javascript in 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 php code 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.我像在第一个代码中那样修改它然后我按照我需要的方式运行..我希望我可以帮助需要我的案例的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM