4

我在提交表单和 Javascript 确认时遇到问题。基本上,按下“提交”按钮时会调用以下 Javascript。

function confirmation() {
    var answer = confirm("Are you sure you wish to edit?")
    if (answer)
    {
        window.location = "#editform2";
    }
}

但是,当我点击取消而不是确定时,Javascript 正确执行,因为我查看地址栏并且它没有更新为#editform2。但是,表单仍然提交。似乎刷新了页面。以下是表格中的相关部分:

//Form is encoded in PHP
<form method=\"post\">
//Form is in here
<input type=\"submit\" value=\"Edit\" onclick=\"confirmation()\">

所以表单不知道它要去哪里,它只是刷新页面,而页面恰好也是处理器。因此,即使我单击了取消,它仍在处理中,并且 Javascript 应该将它保持在同一页面上。除了将处理移动到不同的页面之外,我的解决方案是什么?

4

3 回答 3

6

它的工作原理是这样的,因为它是一个 sumbit 按钮,并且在每种情况下都会提交表单。为表单分配一个 id 并更改输入类型:

<form method="post" id="formid">
<input type="button" value="Edit" onclick="confirmation()">

并在点击时调用此函数:

function confirmation() {
    var answer = confirm("Are you sure you wish to edit?")
    if (answer)
    {
        document.getElementById("formid").submit();
    }
}
于 2009-08-31T07:56:57.507 回答
4

不要使用提交按钮的 onclick 事件,使用表单的 onsubmit 事件:

document.forms[0].onsubmit = function () {
    return confirm("Are you sure you wish to edit?");
}

您可能希望在表单中添加一个 id 属性来识别它。

保持 JavaScript 代码上的事件绑定;不在 HTML 上的内联属性上,使您的代码更易于维护和调试。

于 2009-08-31T08:01:57.323 回答
1

尝试:

return answer;

在函数的末尾并确保 onclick 方法返回 this。像这样:

<input type="submit" value="Edit" onclick="return confirmation()">

这将使函数返回 false 并且不会发布表单。

于 2009-08-31T07:54:35.840 回答