取消按钮不适用于确认窗口

Cancel button not working for the confirm window

本文关键字:确认 窗口 适用于 不适用 按钮 取消      更新时间:2024-06-24

我正在尝试验证JavaScript中的单选按钮,这是我的代码:

if (document.ExamEntry.GCSE.checked == true) {
    confirm("You have selected GCSE. Is this correct?");
}
if (document.ExamEntry.AS.checked == true) {
    confirm("You have selected AS. Is this correct?");
}
if (document.ExamEntry.A2.checked == true) {
    confirm("You have selected A2. Is this correct?");
}

确认窗口显示,单击"提交"成功将带您进入下一页,但取消按钮似乎不起作用——它只是在我希望它停留在页面上时带您进入该页面,以便您可以更改选项。

我试过一些东西,比如返回结果;结果=错误

它们要么不起作用,要么起作用,反之亦然,因此取消按钮通过保持在同一页面上起作用,但提交按钮也会发生这种情况。

查看confirm上的文档。上面写着,

结果是一个布尔值,指示是否选择了OK或Cancel(true表示OK)

这意味着您的每一行都应该检查返回值。一种简洁的方法是,例如:

if (!confirm("You have selected A2. Is this correct?")) {
    // event.cancel = true, or whatever you need to do on your side to cancel
} // otherwise fall through and do what you're doing.

现在的情况是,由于您从未考虑过confirm的返回值,因此您总是陷入"成功"的情况。

var gcse = true, 
    as   = true,
    a2   = true;
if (document.ExamEntry.GCSE.checked == true) {
    gcse = confirm("You have selected GCSE. Is this correct?"));
}
if (document.ExamEntry.AS.checked == true) {
    as = confirm("You have selected AS. Is this correct?");
}
if (document.ExamEntry.A2.checked == true) {
    a2 = confirm("You have selected A2. Is this correct?");
}
if (gcse && as && a2) {
    // you're golden
    window.location.href = 'otherpage'
}
if (document.ExamEntry.GCSE.checked == true) { 
    if(confirm("You have selected GCSE. Is this correct?")) {
        // do something
    }
} if (document.ExamEntry.AS.checked == true) {
    if(confirm("You have selected AS. Is this correct?")) {
        // do something
    }
}  
if (document.ExamEntry.A2.checked == true) {
    if(confirm("You have selected A2. Is this correct?")) {
        //do something
    }
}