繁体   English   中英

单击确认对话框的“取消”按钮时页面重定向

[英]Page redirect on clicking of “Cancel” button of a confirm dialogue

请查看代码段-

<form action="post" onsubmit="return confirm('Are You Sure?')">
       <a id="saveBtn" class="btnClass">Save<a/>
</form>

当我单击“保存”,然后单击“ 确定 ”按钮以确认弹出窗口时,将表单提交。 如果我单击“ 取消 ”,则不提交表单,并且我离开了当前页面。 如果我单击“ 取消 ”按钮,然后页面重定向到其他页面,是否可以?

您可能不应该使用onsubmit属性,而应采用不引人注目的事件侦听器方法,以提高可读性和可维护性。

这样的内容应该可以显示总体思路,您可以使用自己的重定向链接对其进行更新:

var submitLink = document.getElementById('saveBtn'),
    myForm = document.getElementById('myForm');

submitLink.addEventListener('click', function(e) {
    if (confirm('Are You Sure?')) {
        myForm.submit();
    } else {
        e.preventDefault();
        window.location = 'http://google.com'; // redirect to your own URL here
    }
});

这依赖于具有id属性的表单和锚点:

<form action="post" id="myForm">
   <a href="#" id="saveBtn" class="btnClass">Save<a/>
</form>

是的,您可以这样做,因为确认将返回true / false,您可以为错误的结果编写其他行为,例如:

<form action="post" onsubmit="return confirm('Are You Sure?')? true:window.location.assign('http://www.w3schools.com')">
   <a id="saveBtn" class="btnClass">Save<a/>

您可以通过将状态等同为true或false来处理确认对话框。

function myFunction() {
 var r = confirm('Are You Sure?');
 if(r==true) 
 return true;
 else {
    event.preventDefault();
    window.location="http://example.com";
 }
}

这是一个有效的小提琴https://jsfiddle.net/BoyWithSilverWings/p7knLr3m/

暂无
暂无

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

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