Why is it possible to access form values in the in

2019-08-17 19:34发布

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.

3条回答
太酷不给撩
2楼-- · 2019-08-17 20:08

This could help you:

3 solutions:

  1. Using the Function constructor
  2. Assigning variables as properties of the element
  3. Using scope to remember the instances of the local variables

Read more here, hope it helps you, Cheers!

http://www.howtocreate.co.uk/referencedvariables.html

查看更多
三岁会撩人
3楼-- · 2019-08-17 20:09

It seems that the browser is assigning theInput behind the scenes. The reason it's not working in your second case is because you're looking for theInput in the scope of the submitHandler function, not the scope of the actual event handler. It works if you pass theInput into submitHandler in your HTML onsubmit, even if you change the variable name in submitHandler.

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

Furthermore, it fails if you change submitHandler(theInput) to something else, see below:

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

查看更多
乱世女痞
4楼-- · 2019-08-17 20:23

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>

enter image description here

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.

查看更多
登录 后发表回答