html - HTML 解析期间范围发生变化

标签 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" 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/

相关文章:

scope - 重新绑定(bind)在 for 循环中不起作用的变量

javascript - 如何在 JavaScript 中使用 CSS

javascript - 如何使用最小/最大高度和高度将响应式 CSS 高度应用于元素?

Javascript 最佳实践——在 DOM 中隐藏元素或生成 DOM 元素

javascript - 我的 if 语句是否忽略了我的条件?

javascript - 如何使用 Javascript 获取元素的名称?

java - 如果我直接声明并访问类的属性有什么区别?

html - 将多个<ul>分成平衡列

javascript - 无法将提交按钮映射到 thymeleaf 中的 "/submit"api 调用

JavaScript: "function onload() {}"与 "onload = function() {}"有何不同?