如果您像这样在 HTML 中创建一个表单:
<!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>
当 input
标签被解析时(至少在 chrome 中),相应的 DOM 元素显然会以表单作为范围创建,因此绑定(bind)到 onclick 处理程序的函数将是 form.submit()
而不是 window.submit()
。这是标准行为还是依赖于浏览器?是否有任何文档涵盖此内容?
最佳答案
WHATWG HTML 标准在事件处理程序属性中定义了它 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).
在这种情况下,由于表单所有者不为空,因此表单的每个属性都在范围内。 “submit”是表单的一个属性,所以“submit()”将调用 form.submit()。
关于html - HTML 解析期间范围发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296881/