首页 > 解决方案 > Why is it possible to access form values in the inline event handler?

问题描述

I just realized that inside a form event handler (like onsubmit or oninput etc), you can access control values globally, meaning the following does indeed work:

<form onsubmit="alert(theInput.value); return false">
  <input name="theInput">
</form>

Why does this work? I never defined theInput anywhere and it is also not a global variable.

Assuming that the internal browser code assigns those variables itself, why cant I access theInput in a custom event handler?

function submitHandler() {
  alert(theInput.value)
}
<form onsubmit="submitHandler(); return false">
  <input name="theInput">
</form>

In submitHandler(), theInput is undefined and the code breaks, as I expected.

Is there any documentation available about this? Could not find any, but it is admittedly something hard to search for. MDN docs even use this syntax in one of their examples.

标签: javascripthtml

解决方案


内联处理程序(不直观)似乎在 a 内运行with(this),其中this处理程序所在的元素是:

<form onsubmit="debugger; console.log(theInput.value); return false">
  <input name="theInput">
  <button>submit</button>
</form>

在此处输入图像描述

document也被编辑with了。

从 a<form>中,您可以通过点符号访问具有特定名称的输入,因此引用的工作方式与内联处理程序中的引用theInput.value一样。this.theInput.value

解决方案:永远不要使用内联处理程序,它们太疯狂了。


推荐阅读