仅通过 ID 引用 Javascript 中的 HTML 元素
显然,HTML 元素的 id 被加载到 HTML 页面上 Javascript 的全局命名空间中。因此,如果我有像这样的 HTML:
<p id="mypara">Hello</p>
我可以像这样运行 Javascript:
mypara.innerText += " world";
这会导致该段落在 Windows 上的 IE9 和 Chrome 中将“Hello world”作为其文本。这似乎是一种比标准更方便的引用 HTML 元素的方法
document.getElementById("mypara").innerText += " world";
据我所知,缺点似乎是你不能给出作为 Javascript 关键字的 HTML 元素 id(看起来不错)并且你的全局命名空间污染更严重。
这种方法还有其他问题吗?是否有任何文档准确描述浏览器何时/如何完成全局命名空间的填充?有怪癖或陷阱吗?有人做过浏览器兼容性测试吗?
Apparently the ids for HTML elements get loaded into the global namespace for Javascript on an HTML page. As such, if I have HTML like:
<p id="mypara">Hello</p>
I can run Javascript like:
mypara.innerText += " world";
which results in the paragraph having "Hello world" as its text in IE9 and Chrome on Windows. This seems like a more convenient way to refer to HTML elements than the standard
document.getElementById("mypara").innerText += " world";
As far as I can tell, the cons seem to be that you can't give HTML elements ids that are Javascript keywords (doesn't seem so bad) and your global namespace is more polluted.
Are there any other problems with this approach? Is there any documentation that describes exactly when/how the population of the global namespace is done by browsers? Are there quirks or pitfalls? Has anyone done any browser compatibility testing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
早期 IE 引入了对元素进行元素 id 和名称全局引用的做法。它从未标准化,被认为是一个非常糟糕的主意。
其他浏览器为与 IE 编写的网站兼容的做法提供了各种级别的支持,但通常支持很少(甚至在某种程度上隐藏)以阻止其使用。某些浏览器仅在怪异模式或某些 DOCTYPE 下支持它。
它仍然被认为是一个非常糟糕的主意,不要使用它。使用适当的 DOM 方法,不要依赖此类浏览器怪癖。
Early IE introduced the practice of making element ids and names global references to the elements. It was never standardised and was considered a very bad idea.
Other browsers provided various levels of support for the practice to be compatible with sites written for IE, but generally support was minimal (even hidden to some extent) to discourage its use. Some browsers only supported it in quirks mode or with certain DOCTYPEs.
It is still considered a very bad idea, do not use it. Use appropriate DOM methods, don't rely on such browser quirks.
我会担心脚本在旧浏览器中的工作情况。例如,这个小提琴在 Firefox 3 中不起作用。
http://jsfiddle.net/rrSwW/
I would worry about the script working in older browsers. For example this fiddle does not work in Firefox 3.
http://jsfiddle.net/rrSwW/