在 Confirm() 方法中单击“取消”与单击“确定”具有相同的结果

问题描述

我是在我的 HTML 代码中实现确认方法的初学者 - 当用户点击“x”时,他们将被重定向到主页。否则,什么都不会发生。

我的问题是在 confirm() 中,“确定”和“取消”选项都重定向到主页,我不知道为什么。

我看到很多人有类似的问题,查看了很多论坛并注意到在大多数情况下写 onclick="return confirmCancel() 而不是 onclick="confirmCancel()" 有帮助,但它并没有解决我的问题。

>

HTML:

<a onclick="return confirmCancel()"><img src="assets/cancel.svg"></a>

JS:

const confirmCancel = () => {
    confirm("All your progress will be lost. Are you sure you want to leave?");
    if (confirmCancel) {
        window.location.assign("index.html");
    } else {
        return false;
    }
}

解决方法

试试这样的方法。

<a onclick="pleaseConfirm"><img src="assets/cancel.svg"></a>
const pleaseConfirm = () => {
  if (confirm("All your progress will be lost. Are you sure you want to leave?")) {
    window.location.assign("index.html");
  }
}
,

您需要测试confirm的返回值(而不是confirmCancel函数的真实性)。

const confirmCancel = () => {
    if (confirm("All your progress will be lost. Are you sure you want to leave?");) {
        window.location.assign("index.html");
    } else {
        return false;
    }
}
,

您大部分时间都在那里 .. 您需要检查 confirm() 是否为真.. 更改:

confirm("All your progress will be lost. Are you sure you want to leave?");
    if (confirmCancel)

var test_confirm = confirm("All your progress will be lost. Are you sure you want to leave?");
    if (test_confirm === true)

简写可以

 if (confirm("All ... ... "){
,

您可以在 JavaScript 中执行功能,而不是在 HTML 标签中调用 JavaScript 函数

<a id="btn-exit"><img src="assets/cancel.svg"></a>

var btnExit = document.querySelector('#btn-exit')
btnExit.addEventListener('click',() => {
  if (confirm("are you sure?")) {
    window.location.assign("index.html");
  }
})