我的困境相当简单:这个函数获取 id
'这个' <li>
基于父级的元素 id
的 <ul>
.它以前工作正常但现在不行了,我要么需要 <ul>
使用 class
es 而不是 id
同时仍然能够分配 id
将 'current' 添加到当前元素,或者更改我的 css。
function myFunction(element) {
liArray = document.getElementById("leftlist").childNodes;
i = 0;
while (liArray[i]) {
liArray[i].id = "";
i++;
}
element.id = "current"; // or element.className ?
}
ul#leftlist {
background-color: rgb(205, 205, 205);
}
ul#leftlist li#current a {
color: rgb(96, 176, 255);
background-color: 218, 218, 218);
}
ul#leftlist li a {
color: rgb(86, 86, 86);
}
#leftlist a:link {
color: rgb(86, 86, 86);
background-color: #ddd;
}
#leftlist a:active {
color: rgb(96, 176, 255);
background-color: rgb(218, 218, 218);
}
<ul id="leftlist">
<li onClick='myFunction(this);'>
<a href="123" bla bla </a></li>
<li onClick='myFunction(this);'> .... etc.</li>
</ul>
也许我需要更改我的 CSS。这以前有效,但现在是当前的 id
不像ul#leftlist li a
那样有效即使我分配 id="current"
也优先通过 JavaScript。
最佳答案
你应该为“当前”之类的东西使用类,而不是 id。 id 通常不应该改变,并且“当前”不是一个很好的 id,因为您可能在某个页面上有一堆在某种程度上是“当前”的东西。如果你需要一些 css 样式来覆盖另一个,你可以用 !important 强制它:
ul#leftlist li.current a {
color: rgb(96,176,255) !important;
background-color:218,218,218) !important;
}
关于JavaScript函数到 'get element by parent class'并赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/226088/