HTML解析期间作用域的更改
如果您像这样以HTML创建表单:HTML解析期间作用域的更改,html,dom,scope,Html,Dom,Scope,如果您像这样以HTML创建表单: <!DOCTYPE html> <html><head> <script> function submit() { console.log("window.submit"); } </script> </head> <body> <form name="form"> <input type="button" value="button" oncl
<!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>
函数提交(){
console.log(“window.submit”);
}
解析
input
标记时(至少在chrome中),显然会创建相应的DOM元素,将表单作为作用域,这样绑定到onclick处理程序的函数将是form.submit()
,而不是window.submit()
。这是标准行为还是浏览器相关?是否有任何文档介绍了这一点?WHATWG HTML标准在事件处理程序属性中定义了它
范围
- 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).
在这种情况下,由于表单所有者不为null,因此表单的每个属性都将在范围内。“submit”是form的一个属性,因此“submit()”将调用form.submit()。可能与有关。几乎与步骤10“词汇环境范围”中的定义相同