JavaScript窗口对象元素属性 [英] JavaScript window object element properties

查看:50
本文介绍了JavaScript窗口对象元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个同事向我展示了以下代码,并问我为什么起作用。

 < span id = myspan> ;您喜欢我的帽子吗?< / span> 
< script type = text / javascript>
var spanElement = document.getElementById( myspan);
alert( Here I am! + spanElement.innerHTML + \n + myspan.innerHTML);
< / script>

我解释了浏览器在浏览器上附加了一个属性,该属性带有元素ID的名称。解析文档,该文档然后包含对相应dom节点的引用。就像在渲染页面时在后台调用 window.myspan = document.getElementById( myspan)一样。



随后的讨论中,我们提出了一些问题:




  • 窗口对象和大多数DOM不是官方JavaScript / ECMA标准的一部分,但是上述行为是否已在其他任何官方文献中得到了记录,也许与浏览器相关?


  • 以上方法有效在浏览器中(至少是主要竞争者),因为有一个窗口对象,但在犀牛之类的设备中却失败了。编写依赖于这种做法的代码是否被认为是不好的做法,因为它对执行环境做出了太多假设?


  • 是否存在任何上述浏览器都会失败的浏览器,还是这被认为是全面的标准行为?




这里有人知道这些问题的答案并且愿意启发我吗?我尝试了快速的互联网搜索,但是我承认我不确定如何正确地表达查询内容。欢迎使用指向参考和文档的指针。

解决方案

这是非标准的仅限IE行为,不应使用。 / p>

[1] [2] [3]


A coworker showed me the following code and asked me why it worked.

<span id="myspan">Do you like my hat?</span>
<script type="text/javascript">
var spanElement = document.getElementById("myspan");
alert("Here I am! " + spanElement.innerHTML + "\n" + myspan.innerHTML);
</script>

I explained that a property is attached to the window object with the name of the element's id when the browser parses the document which then contains a reference to the appropriate dom node. It's sort of as if window.myspan = document.getElementById("myspan") is called behind the scenes as the page is being rendered.

The ensuing discussion we had raised a few of questions:

  • The window object and most of the DOM are not part of the official JavaScript/ECMA standards, but is the above behavior documented in any other official literature, perhaps browser-related?

  • The above works in a browser (at least the main contenders) because there is a window object, but fails in something like rhino. Is writing code that relys on this considered bad practice because it makes too many assumptions about the execution environment?

  • Are there any browsers in which the above would fail, or is this considered standard behavior across the board?

Does anyone here know the answers to those questions and would be willing to enlighten me? I tried a quick internet search, but I admit I'm not sure how to even properly phrase the query. Pointers to references and documentation are welcome.

解决方案

This is a non-standard IE-only behavior and should not be used.

[1] [2] [3]

这篇关于JavaScript窗口对象元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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