Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                    
                
        

我有很多这样的代码行,以及如何减少这些行。还请解释您的代码。如果有编写此类逻辑代码的简便方法,请发布链接。

$(function () {
  $("#menu1").click(function () {
    $(this).css({"background-color": "rgba(255, 255, 255, 0.4)"});
    $("#menu2").css({"background-color": "transparent"});
    $("#menu3").css({"background-color": "transparent"});
    $("#menu4").css({"background-color": "transparent"});
    $("#menu5").css({"background-color": "transparent"});
  });

  $("#menu2").click(function () {
    $(this).css({"background-color": "rgba(255, 255, 255, 0.4)"});
    $("#menu1").css({"background-color": "transparent"});
    $("#menu3").css({"background-color": "transparent"});
    $("#menu4").css({"background-color": "transparent"});
    $("#menu5").css({"background-color": "transparent"});
  });

  $("#menu3").click(function () {
    $(this).css({"background-color": "rgba(255, 255, 255, 0.4)"});
    $("#menu1").css({"background-color": "transparent"});
    $("#menu2").css({"background-color": "transparent"});
    $("#menu4").css({"background-color": "transparent"});
    $("#menu5").css({"background-color": "transparent"});
  });
});

最佳答案

使用jquery Attribute starts with selector.not()。尝试这个:

$(function(){
     $("[id^=menu]").click(function(){
          $(this).css({"background-color":"rgba(255, 255, 255, 0.4)"});
          $("[id^=menu]").not(this).css({"background-color":"transparent"});
     });
});

07-24 19:23