今天我偶然发现了在Javascript中访问DOM元素的可能性,只需通过它的id,例如:
elementid.style.backgroundColor = "blue"
Run Code Online (Sandbox Code Playgroud)
我测试了一个非常短的片段,如果这适用于IE,Firefox和Chrome - 它确实如此.这是我使用的片段:
<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>
Run Code Online (Sandbox Code Playgroud)
所以我想知道document.getElementById('elementid')应该使用哪些情况(或类似的框架替换,如$())以及直接访问的缺点是什么.
我无法找到任何有用的文档.无处不在getElementById或使用框架方法.