2017-04-13 72 views
0

您好,非常感谢您的帮助!美化效率低下的代码

我对编码非常陌生,并且花了相当多的时间想出这段代码。幸运的是它的工作原理:-)它的功能是将一个多步段的导航元素设置为主动....我知道这是非常低效的编码,但我还没有技能,使其更有效率。你能帮我吗?谢谢soooo多谢,谢谢!

$('#Step1').click(function(){ 
     $('#Step1').addClass('Step-item-active'); 
     $('#Step2').removeClass('Step-item-active'); 
     $('#Step3').removeClass('Step-item-active'); 
     $('#Step4').removeClass('Step-item-active'); 

    }); 
    $('#Step2').click(function(){ 
     $('#Step2').addClass('Step-item-active'); 
     $('#Step3').removeClass('Step-item-active'); 
     $('#Step4').removeClass('Step-item-active'); 
     $('#Step1').removeClass('Step-item-active'); 

    }); 
    $('#Step3').click(function(){ 
     $('#Step3').addClass('Step-item-active'); 
     $('#Step4').removeClass('Step-item-active'); 
     $('#Step1').removeClass('Step-item-active'); 
     $('#Step2').removeClass('Step-item-active'); 

    }); 
    $('#Step4').click(function(){ 
     $('#Step4').addClass('Step-item-active'); 
     $('#Step1').removeClass('Step-item-active'); 
     $('#Step2').removeClass('Step-item-active'); 
     $('#Step3').removeClass('Step-item-active'); 

    }); 
+0

使用类,而不是ID的。然后将一个处理函数绑定到具有该类的所有元素,然后在您为当前元素('$(this)') – CBroe

回答

2

你可以给他们所有的班级。例如class="step"。 (忘了的ID)

然后你就可以添加一个点击功能,对所有这些作品

$(".step").click(function(){ 
    // remove the class from all of them 
    $(".step").removeClass("Step-item-active") 
    // add the class to the clicked element 
    $(this).addClass("Step-item-active") 
}); 
+0

特别添加它之前,首先从该类中的所有项中移除该类。完美的作品!非常感谢! :-) – christian

0

类,而不是ID和四行代码。

$('.Step').click(function() { 
 
    $('.Step-item-active').removeClass('Step-item-active'); 
 
    $(this).addClass('Step-item-active'); 
 
});
div { 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: blue; 
 
} 
 

 
.Step-item-active { 
 
    background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div class="Step"></div> 
 
<div class="Step"></div> 
 
<div class="Step"></div> 
 
<div class="Step"></div>