The issue is the scope chain of functions compiled from HTML element attribute values declared in HTML source. Attributes of the form on_eventName=functionBodyCode
exhibit this behavior.
For historical reasons (the DOM did not exist in its current form, document.getElementByID
had yet to be invented...) such functions are compiled with a scope chain comprising the object on which the event handler attribute is provided, any form
element the element is within, and the document
object. However different browsers took different approaches when emulating Netscape behavior. Some browsers included any and every parent object of an element providing an event handler attribute, while others omitted some pertinent objects such as document
.
Technical detail may be found in "Javascript the definitive guide" O'Reilly, section "19.1.6. Scope of Event Handlers".
The main recommendation is to avoid supplying event handlers in HTML - add them in JavaScript using addEventListener
instead. If for some reason function calls must be coded in HTML attribute values, avoid using function names that are methods of DOM objects.
Note the custom scope chain for event handlers only applies to functions generated from HTML attributes. It does not apply to functions created in JavaScript and added to an element using addEventListener
or element.onEventName=aFunctionObject
.
The following snippet demonstrates locating property names of outer elements in the scope chain of event handlers defined in HTML: :
<form name="formName1" action="">
<p> Try to access the elements collection of the form:
<button type="button"
onclick="console.log( elements);">elements
</button>
</p>
</form>
<form name="formName2" action="" onsubmit="return false">
<p> Try to access form name as form.name:
<button type="button"
onclick="console.log( 'form.name: %s', form.name);">form.name
</button>
</p>
</form>
<form name="formName3" action="" onsubmit="return false">
<p>Access document.write as "write"
<button type="button"
onclick="console.log( 'write: %s', write);">write
</button>
</p>
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…