将锚点的href属性与“#”进行比较?

时间:2015-03-10 14:18:18

标签: javascript html css href

我想更改所有锚点的css属性,并将href设置为"#"。

<div class="mlItems">
    <a href="#">Home</a>
</div>
<div class="mlItems">
    <a href="applets.html">Applets</a>
</div>
<div class="mlItems">
    <a href="tools.html">Tools</a>
</div>
<div class="mlItems">
    <a href="gallery.html">Gallery</a>
</div>
<div class="mlItems">
    <a href="tutorials.html">Tutorials</a>
</div>
<div class="mlItems">
     <a href="fun.html">Fun</a>
</div>
<div class="mlItems">
      <a href="about.html">About</a>
</div>

所以我使用他们的标签名称搜索元素,并将href与&#34;#&#34;进行比较。使用for循环。然后使用javascript更改元素的样式属性。

function setnavstat(){
var menul = document.getElementsByTagName("a");
for(var i = 0;i < menul.lenght;i++){
    if(menul[i].getAttribute("href") == "#"){ 
         menul[i].style.color = "#000000";
       } 
     }
}

但这似乎不起作用。帮我。提前致谢。如果响应仅限于JavaScript,则会有所帮助。

1 个答案:

答案 0 :(得分:2)

您不需要使用JavaScript,您可以使用纯CSS:

&#13;
&#13;
a[href="#"]{
    color: #000000;
}
&#13;
<div class="mlItems">
    <a href="#">Home</a>
</div>
<div class="mlItems">
    <a href="applets.html">Applets</a>
</div>
<div class="mlItems">
    <a href="tools.html">Tools</a>
</div>
<div class="mlItems">
    <a href="gallery.html">Gallery</a>
</div>
<div class="mlItems">
    <a href="tutorials.html">Tutorials</a>
</div>
<div class="mlItems">
     <a href="fun.html">Fun</a>
</div>
<div class="mlItems">
      <a href="about.html">About</a>
</div>
&#13;
&#13;
&#13;