javascript - 为什么元素的属性出现在内联函数的范围内?

标签 javascript html

给定这段代码:

<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 将返回字符串值)。

这个行为是在哪里指定的?

http://jsfiddle.net/b8mpJ/

最佳答案

因为它是在 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/

相关文章:

javascript - TypeScript 中是否有可用于 HTML 元素的类?

javascript - 浏览器如何解析前端代码中未具体引用的图标库?

html - 表格<TD>右边框问题

Jquery 如果 div 在页面上可见?

javascript - Java 中的 map 集合

javascript - 如何将复选框表单域从一个表单复制到另一个表单?

javascript - 如何限制矩形在 fabricjs 中调整大小/移动到图像之外?

javascript - Mongoose如何查看正在生成哪个mongodb查询,数据库没有返回任何内容

javascript - getElementById 到array 来函数切换

html - CSS Clear Float 不适用于媒体查询