大家好:我很难让这段代码工作:
HTML:
<div id='nav_bar'>
<ul id="ul">
<li onmouseover="test();" > <a href='friends.php' class="first" >Friends</a> </li>
<li onmouseover="test();"> <a href='messages.php' class="first">Messages</a> </li>
<li onmouseover="test();"> <a href='index.php' class="first">Home</a> </li>
<li onmouseover="test();"> <a href='profile.php?id=<?= $prof ?>' class="first">Profile</a></li>
<li onmouseover="test();"> <a href='find_friends.php' class="first">Search</a> </li>
<li onmouseover="test();"> <a href='members.php' class="first">Members</a> </li>
<li onmouseover="test();"> <a href='logout.php' class="first">Log Out</a> </li>
</ul>
</div>
JavaScript:
function test(){
x = document.getElementsByClassName("first");
x.style.backgroundColor = "#ee7600";
x.style.border = "thin solid black";
}
HTML 文件正确引用了 Javascript 文件;我试图在导航栏中使用 class="first"更改每个元素的样式。为什么不会document.getElementsByClass()
工作?
最佳答案
getElementsByClassName
返回一个类似数组的实时 HTMLCollection。
style
是单个 HTMLElement 的属性。
循环遍历 HTML Collection 并依次修改每个集合的样式。
for (var i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "#ee7600";
x[i].style.border = "thin solid black";
}
关于javascript - .getElementsByClassName 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31676708/