我需要隐藏文档中除了特定ID之外的所有“section”元素。
在jquery中,这很容易实现。
在jquery中,这很容易实现。
$("section").hide();
$("section#myId").show();
我不需要使用jQuery,应该如何实现这个功能?(我需要在页面加载时立即执行,且不会被注意到。)我还需要它能够跨浏览器运行。
谢谢。
$("section").hide();
$("section#myId").show();
我不需要使用jQuery,应该如何实现这个功能?(我需要在页面加载时立即执行,且不会被注意到。)我还需要它能够跨浏览器运行。
谢谢。
getElementById
是您的好帮手:
var sections = document.getElementsByTagName('section');
var mySection = null;
for(var i = 0; i < sections.length; ++i) {
if(sections[i].id === "myId") {
mySection = sections[i];
mySection.style.display = "block";
break;
}
sections[i].style.display = "none";
}
将以下内容放在HTML中的 </body> 标签之前
<script>
(function () {
for(var els = document.getElementsByTagName ('section'), i = els.length; i--;)
els[i].id !== "myId" && (els[i].style.display = "none");
}) ();
</script>
或在“现代”(HTML5)浏览器中:
<script>
[].forEach.call (document.querySelectorAll ('section'),
function (el) { el.id !== "myId" && (el.style.display = "none"); })
</script>