为什么可以在内联事件处理程序中访问表单值? [英] Why is it possible to access form values in the inline event handler?

查看:72
本文介绍了为什么可以在内联事件处理程序中访问表单值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档也是 .

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

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

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.

解决方案

Inline handlers (unintuitively) appear to run inside a with(this), where this is the element that the handler is on:

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

The document is also withed as well.

From a <form>, you can access an input with a particular name via dot notation, so referencing theInput.value works just like referencing this.theInput.value in the inline handler.

Solution: Never use inline handlers, they're crazy.

这篇关于为什么可以在内联事件处理程序中访问表单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆