2016-07-10 11 views
3

Wenn Sie ein Formular in HTML wie so erstellen:Scope Änderungen während der HTML-Analyse

<!DOCTYPE html> 
<html><head> 
<script> 
function submit() { 
    console.log("window.submit"); 
} 
</script> 
</head> 
<body> 
<form name="form"> 
    <input type="button" value="button" onclick="submit()" /> 
</form> 
</body> 
</html> 

Wenn der input Tag wird analysiert (in Chrom zumindest), wird das entsprechende DOM-Element offenbar mit der Form erzeugt werden, wie der Gültigkeitsbereich, so dass die an den onclick-Handler gebundene Funktion form.submit() statt window.submit() ist. Ist dieses Standardverhalten oder Browser abhängig? Gibt es Unterlagen, die dies abdecken?

+0

Könnte verwandt werden mit [Uncaught TypeError: lang ist keine Funktion] (http://stackoverflow.com/q/38276407/4642212). – Xufox

Antwort

1

Der WHATWG HTML-Standard in Event-Handler definiert Attribute https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes

Scope

- If H is an element's event handler, then let Scope 
    be NewObjectEnvironment(document, the global environment). 
    - Otherwise, H is a Window object's event handler: let Scope be the global environment. 
    - If form owner is not null, let Scope be NewObjectEnvironment(form owner, Scope). 
    - If element is not null, let Scope be NewObjectEnvironment(element, Scope). 

In diesem Fall, da Form Eigentümer nicht null ist, wird jede Eigenschaft des Formulars im Rahmen sein. "submit" ist eine Eigenschaft von form, also "submit()" ruft form.submit() auf.

+0

Fast die gleiche Definition in https://www.w3.org/TR/html5/webappapis.html#event-handler-attributes in Schritt 10 "Lexical Environment Scope" – progysm