.getElementByClassName不起作用? [英] .getElementByClassName not working?
问题描述
大家好:我很难得到这段代码:
HTML:
< div id ='nav_bar'>
< ul id =ul>
< li onmouseover =test(); > < a href ='friends.php'class =first> Friends< / a> < /锂>
< li onmouseover =test();> < a href ='messages.php'class =first>讯息< / a> < /锂>
< li onmouseover =test();> < a href ='index.php'class =first>主页< / a> < /锂>
< li onmouseover =test();> < a href ='profile.php?id =<?= $ prof?>'class =first>个人资料< / a>< / li>
< li onmouseover =test();> < a href ='find_friends.php'class =first>搜寻< / a> < /锂>
< li onmouseover =test();> < a href ='members.php'class =first>成员< / a> < /锂>
< li onmouseover =test();> < a href ='logout.php'class =first>注销< / a> < /锂>
< / ul>
< / div>
JAVASCRIPT:
function test(){
x = document.getElementsByClassName(first);
x.style.backgroundColor =#ee7600;
x.style.border =薄实黑;
}
HTML文件正确引用了JavaScript文件;我试图在导航栏中用class =first来更改每个元素的样式。为什么不能 document.getElementsByClass()
工作?
getElementsByClassName
返回一个类似数组的实时 HTMLCollection 。
style
是单个 HTMLElement 的属性。
循环HTML集合并修改每个元素的样式
$ b
for(var i = 0; i< x.length; i ++){
x [i] .style.backgroundColor =#ee7600;
x [i] .style.border =薄实黑;
}
Hello everyone: I'm having difficulty getting this code to work:
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";
}
The Javascript file is correctly referenced by the HTML file; I'm attempting to change the style of each element with class="first" in a nav bar. Why won't document.getElementsByClass()
work?
getElementsByClassName
returns an array-like live HTMLCollection.
style
is a property of a single HTMLElement.
Loop over the HTML Collection and modify the style of each one in turn.
for (var i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "#ee7600";
x[i].style.border = "thin solid black";
}
这篇关于.getElementByClassName不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!