简体   繁体   English

如果单击取消按钮,如何使Javascript“ confirm()”取消对新页面的请求?

[英]How can I make Javascript “confirm()” cancel the request for new page if the cancel button is clicked?

First of all I have checked many similar questions on here and other resources, but I'm still unable to find the solution I require. 首先,我在这里和其他资源上检查了许多类似的问题,但是我仍然找不到我需要的解决方案。 I have a button that links to a specific page within my application and I also have a confirm() box that asks if the user wants to continue, if they click ok then the next page should be loaded, if they click cancel the new page should not load, as if the button was never clicked at all. 我有一个链接到我的应用程序中特定页面的按钮,还有一个confirm()框,询问用户是否要继续,如果他们单击确定,则应该加载下一页,如果他们单击取消新页面,不应加载,就好像根本没有单击该按钮一样。 Below is my HTML for the button: 以下是按钮的HTML:

<a href="http://localhost:9000/index">
    <button onclick="myFunction()" type="button" class="btn btn-outline-primary btn-lrg" style="font-size:20px;">CANCEL</button>
</a>

And now my JS for the confirm box: 现在我的JS的确认框:

<script>
  function myFunction() {
    if (confirm("Are you sure you wish to cancel this configuration?")) {
      return true;
    } else {
      return false;
    }
  }
</script>

The issue right now is that your button is triggering the function, however your link is the one that's redirecting. 现在的问题是您的按钮正在触发该功能,但是您的链接正在重定向。

That in mind, wrapping a <button> with an <a> is invalid : 请记住,用<a>包裹<button>无效的

Content model: Transparent , but there must be no interactive content descendant. 内容模型: 透明 ,但必须没有交互式内容后代。

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (eg buttons or other links). 只要其中没有交互内容(例如按钮或其他链接) ,该元素可以被包装在整个段落,列表,表格等等,甚至是整个部分中


Some alternatives: 一些替代方案:

Use a <form> instead of an <a> 使用<form>而不是<a>

 <form action="https://stackoverflow.com"> <button type="submit" onclick="return confirm('Are you sure?')" class="btn btn-outline-primary btn-lrg" style="font-size:20px;">CANCEL</button> </a> 

Remove the <a> entirely 完全删除<a>

 function btnCancel() { if (!confirm("Are you sure?")) return false; location.href = "https://stackoverflow.com"; } 
 <button type="button" onclick="btnCancel()" class="btn btn-outline-primary btn-lrg" style="font-size:20px;">CANCEL</button> 

Remove the <button> entirely 完全删除<button>

 <a href="https://stackoverflow.com" onclick="return confirm('Are you sure?')">Cancel</a> 

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

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