为什么元素的属性出现在内联函数的范围中? [英] Why do an element's attributes appear in the scope of an inline function?

查看:83
本文介绍了为什么元素的属性出现在内联函数的范围中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 < button id =blahonclick =alert(id)>点击ME< /按钮> 

点击此按钮将提示blah。为什么 id 属性变成在 onclick 处理程序范围内可见的变量?



另一个例子:

 < button style =font-size:200%onclick = console.log(style)>点击我< /按钮> 

这里我们看到 style 指的是一个 CSSStyleDeclaration 对象,而不是属性的字符串值。这类似于我们通过引用按钮元素的属性属性的索引或通过像 this.style getAttribute 会返回字符串值)。



p>

http://jsfiddle.net/b8mpJ/

解决方案

因为它是在Web Applications API中指定的。引用 whatWG的生活标准


当用户代理程序要获取事件处理程序H的当前值时,它必须执行以下步骤:



[...]使用上面获得的脚本执行环境,创建一个函数对象:

[...] 词法环境范围


  • 让Scope成为NewObjectEnvironment(文档,全局环境)的结果。如果表单所有者不为null,则让Scope为NewObjectEnvironment(>表单所有者,作用域)的结果。


  • 如果element不为null,那么让Scope作为NewObjectEnvironment(element,Scope)的结果。

  • >

    NewObjectEnvironment()在ECMAScript edition 5中定义第10.2.2.3节。您可能会从 声明中更好地了解其效果(其中它也被使用)。换句话说,当在事件处理函数中查找特定的名称绑定时,也会检查目标元素的属性。


    Given this code:

    <button id="blah" onclick="alert(id)">Click me</button>
    

    Clicking the button will alert "blah". Why does the id attribute become a variable visible within the scope of the onclick handler?

    Another example:

    <button style="font-size:200%" onclick="console.log(style)">Click me</button>
    

    Here we see that style refers to a CSSStyleDeclaration object, rather than the string value of the attribute. This is similar to what we'd get by referencing an index of the button element's attributes property, or through attribute properties like this.style (getAttribute would return the string value instead).

    Where is this behavior specified?

    http://jsfiddle.net/b8mpJ/

    解决方案

    Because it's specified in Web Applications API. Quoting 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() is defined in ECMAScript edition 5 section 10.2.2.3. You may probably know its effect better from with statement (where it's used as well). In other words, the target element's properties are checked as well when looking for a particular name binding in the event handler's function.

    这篇关于为什么元素的属性出现在内联函数的范围中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆