使用return false时,javascript确认(取消)仍然提交表单?

时间:2022-11-23 19:39:27

i am using the following code:

我使用以下代码:

        <form method='POST' action='post.php' style='margin-bottom:0px;'>
        <input type='image' name='close_x' src='imgs/button.png' onclick='confirmClose()'>
        </form>

       function confirmClose() {
            if (confirm('Are you sure you wish to close?')) {
                return true;
            } else {
                return false;
            }
        }

however, when you click cancel in the confirm box, it still submits the form.

但是,当您在确认框中单击取消时,它仍然会提交表单。

Surely the return false should stop this from happening?

当然,返回错误应该可以阻止这种情况发生吗?

Any idea why?

知道为什么吗?

Thanks.

1 个解决方案

#1


1  

Don't use inline event handlers.

不要使用内联事件处理程序。

document.getElementsByName('close_x')[0].onclick = function confirmClose(e) {
  if (!confirm('Are you sure you wish to close?'))
    e.preventDefault();
};
#myform {
  margin-bottom: 0px;
}
<form id="myform" method='POST' action='post.php'>
  <input type='image' name='close_x' src='imgs/button.png'>
</form>

#1


1  

Don't use inline event handlers.

不要使用内联事件处理程序。

document.getElementsByName('close_x')[0].onclick = function confirmClose(e) {
  if (!confirm('Are you sure you wish to close?'))
    e.preventDefault();
};
#myform {
  margin-bottom: 0px;
}
<form id="myform" method='POST' action='post.php'>
  <input type='image' name='close_x' src='imgs/button.png'>
</form>