如何在Jquery中减少这一行

How to reduce this lines in Jquery?

本文关键字:一行 Jquery      更新时间:2023-09-26

我有很多行这样的代码,如何减少这些行。也请解释你的代码。如果有任何简单的方法写这样的逻辑代码,请张贴链接。

$(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"});   
     });            
});

给所有的菜单一个共同的类,并这样做

$('.menu').on('click',function(){
    $('.menu').css({"background-color":"transparent"});
    $(this).css({"background-color":"rgba(255, 255, 255, 0.4)"});
});