通过ID直接访问DOM元素有什么缺点? [英] What are the drawbacks of accessing DOM elements directly by ID?
问题描述
今天我偶然发现了通过Javascript的DOM来访问DOM元素的可能性。像这样:
Today I stumbled upon the possibility to access a DOM element in Javascript simply by its id e.g. like this:
elementid.style.backgroundColor = "blue"
如果在IE,Firefox和Chrome中有效,我用非常短的代码片段进行了测试,而且这样做。
这是我使用的片段:
I tested with a very short snippet if this works in IE, Firefox and Chrome - and it does. Here is the snippet I used:
<html><head>
<script>
function highlight() {
content.style.backgroundColor = "blue";
content.style.color = "white";
}
</script>
</head>
<body>
<div id="content">test content</div>
<div onclick="highlight()">highlight content</div>
</body></html>
所以我想知道在哪些情况下 document.getElementById('elementid')<应该使用/ code>(或像$()类似的框架替换),直接访问的缺点是什么。
So I wondered in which cases document.getElementById('elementid')
should be used (or similar framework replacements like $()) and what are the drawbacks of the direct access.
我无法找到任何有用的文件。使用 getElementById
或框架方法的任何地方。
I was not able to find any useful documentation on this. Everywhere either getElementById
or framework methods are used.
推荐答案
微软gubbins。它在许多浏览器中不起作用特别是在标准模式下(您希望标准模式避免怪癖模式不一致,如IE得到 width
错误)。
It is propriety Microsoft gubbins. It doesn't work in lots of browsers — especially in standards mode (and you want standards mode to avoid quirks mode inconsistencies such as IE getting width
wrong).
这篇关于通过ID直接访问DOM元素有什么缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!