Javascript return confirm() 当输入 name=confirm 给出 confirm 不是一个函数

Javascript return confirm() when input name=confirm gives confirm is not a function

我的代码在控制台中显示此错误:

Uncaught TypeError: confirm is not a function

我可以通过将输入重命名为“确认”以外的名称来解决它。
为什么命名输入会与 JavaScript 的确认功能冲突?

<form action="" method="POST">
  <input type="text" name="confirm">
  <input type="submit" onclick="return confirm('Text')">
</form>

在JavaScript中,输入元素的名称成为关联表单对象的属性。在您的例子中,名为“confirm”的输入成为其形式的 属性,即 shadows the confirm method inherited from the window object.

window.confirm => form.confirm
<input type="text" name="confirm"> => form.confirm

如上面评论中的,可以使用window.confirm()来确保访问window对象的confirm方法。

<form action="" method="POST">
  <input type="text" name="confirm">
  <input type="submit" onclick="return window.confirm('Text')">
</form>

或者,如您的问题所述,使用不同的输入名称:

<form action="" method="POST">
  <input type="text" name="confirmation">
  <input type="submit" onclick="return confirm('Text')">
</form>


更多参考,另见:

HTMLFormElement

Warning: Avoid giving form elements a name that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.

input name called submit
confirm is not a function