javascript - 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.
解决方案
内联处理程序(不直观)似乎在 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
解决方案:永远不要使用内联处理程序,它们太疯狂了。
推荐阅读
- python - 特定于 azkaban 流程的每次执行的 python 虚拟环境
- pandas - 将带有 start_date 和 end_date 的行转换为每日行
- javascript - 以不同的页面大小导出地图
- python - 如何删除python matploylib中的无点区域
- string - split_on_char OCaml 的未绑定记录字段
- php - php解析url并删除参数问题
- format - 仅将 ESLint / Prettier 应用于选定的行
- angularjs - 我可以与 Angular 的 Redshfit 联系以进行报告吗?
- excel - VBA使用ColumnBound在组合框中选择值
- reactjs - React 状态变量的特殊操作