循环更改某些元素的样式

时间:2018-11-21 15:33:12

标签: javascript css ajax

我在布局页面的顶部有这个navBar:

<div id="myTopnav" class="topnav" style="background-color: #030005; background-image: linear-gradient(#270133,#F5F5F5)">
            <a href="#" class="active ">@Session["UserName"].ToString() @Session["UserApe"].ToString()</a>
            <a href="#">Testing A</a>
            <a href="#">Testenado B</a>
            <a href="/Home/Logout">Cerrar Sesion</a>
            <a href="javascript:void(0);" class="icon" onclick="despMenu()"><i class="fa fa-bars"></i></a>
        </div>

我的想法是在每个按钮上切换渐变色

window.addEventListener("load",inicializarEventos,false);
function inicializarEventos() {
    var ob1 = document.getElementById("myTopnav");
    var lista = ob1.getElementsByTagName("a");    
    var sw = 1;
    for (var i = 0; i < (lista.length - 1); i++) {
        if (sw == 1) {
            ob1.item(i).style.backgroundImage="linear-gradient(to top ,#270133,#F5F5F5)";            
            sw = 0;
            console.log("Entro a 1")
            break;
        }
        else {
            ob1.item(i).style.backgroundImage = "linear-gradient(to top ,#F5F5F5,#270133)";
            sw = 1;
            console.log("Entro a 2")
             }
      }
}

但是它不起作用。我究竟做错了什么?有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您的工作示例应如下所示:

window.addEventListener("load",inicializarEventos,false);
function inicializarEventos() {
    var ob1 = document.getElementById("myTopnav");
    var lista = ob1.getElementsByTagName("a");    
    var sw = 1;
    for (var i = 0; i  < lista.length; i++) {
        if (sw == 1) {
            lista[i].style.backgroundImage="linear-gradient(to top ,#270133,#F5F5F5)";            
            sw = 0;
            console.log("Entro a 1")
            break;
        }
        else {
            lista[i].style.backgroundImage = "linear-gradient(to top ,#F5F5F5,#270133)";
            sw = 1;
            console.log("Entro a 2")
             }
      }
}

如上所述,您应该使用lista[i]访问当前对象,并且如果没有限制i < lista.length

,也应该检查整个列表