给定这段代码:
<button id="blah" onclick="alert(id)">Click me</button>
点击按钮会提示“blah”。为什么 id
属性成为在 onclick
处理程序范围内可见的变量?
另一个例子:
<button style="font-size:200%" onclick="console.log(style)">Click me</button>
这里我们看到 style
指的是一个 CSSStyleDeclaration
对象,而不是属性的字符串值。这类似于我们通过引用按钮元素的 attributes
属性的索引或通过 this.style
(getAttribute
将返回字符串值)。
这个行为是在哪里指定的?
最佳答案
因为它是在 Web 应用程序 API 中指定的。引用 whatWG's Living Standard :
When the user agent is to get the current value of the event handler H, it must run these steps:
[...] Using the script execution environment obtained above, create a function object with:
[...] Lexical Environment Scope
Let Scope be the result of NewObjectEnvironment(document, the global environment).
If form owner is not null, let Scope be the result of NewObjectEnvironment(>form owner, Scope).
If element is not null, let Scope be the result of NewObjectEnvironment(element, Scope).
NewObjectEnvironment() 在 ECMAScript 版本 5 中定义 section 10.2.2.3 .您可能从 with 中可以更好地了解它的效果声明(也使用它的地方)。换句话说,在事件处理程序函数中查找特定名称绑定(bind)时,也会检查目标元素的属性。
关于javascript - 为什么元素的属性出现在内联函数的范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766922/