I noticed that you can call submit()
in event handlers of form elements. For example,
<input id="myInput" type="button" onclick="submit()" value="Test" />
clicking the button generated by the code above will submit the form. The funny thing is, I can't call submit()
outside开发者_运维知识库 the event handler. There is no submit
member defined for the input element.(document.getElementById("myInput").submit
is undefined
.) So, where is this function defined, and where can I find a reference to this function?
It is described here in section 19.1.6:
Event handlers defined as HTML attributes have a more complex scope chain (...)
and
The scope chain of an event handler does not stop with the object that defines the handler: it proceeds up the containment hierarchy. For the
onclick
event handler described earlier, the scope chain begins with the call object of the handler function. Then it proceeds to the Button object, as we've discussed. After that, it continues up the HTML element containment hierarchy and includes, at a minimum, the HTML<form>
element that contains the button and theDocument
object that contains the form. The precise composition of the scope chain has never been standardized and is implementation-dependent. Netscape 6 and Mozilla include all containing objects (even things such as<div>
tags), while IE 6 sticks to a more minimal set that includes the target element, plus the containing Form object (if any) and the Document object. Regardless of the browser, the final object in the scope chain is the Window object, as it always is in client-side JavaScript.
So I guess it was already clear that the submit
function is the one of the form
. And if the event handler is defined via an HTML attribute, then the scope chain are the element itself and its parents. But it is not standardized, so one should not rely on that behavior.
You'll notice you get the same error with the following:
<input id="myInput" type="button" onclick="this.submit()" value="Test" />
That is, submit() is not a method of the HTMLInputElement, but submit() is resolving to the Form's submit() function.
For example:
<form action='test.php' method='get' id='myForm'>
<input id="myInput" type="button" onclick="Foo()" value="Test" />
</form>
<script type='text/javascript'>
document.getElementById('myForm').Foo = function() {
alert('Bar!');
};
</script>
Clicking the button alerts 'Bar!'.
精彩评论