我有这么多行代码以及如何减少这些行.还请解释你的代码.如果有任何简单的方法来编写这样的逻辑代码请发布链接.
$(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"});
});
});
Run Code Online (Sandbox Code Playgroud)
使用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"});
});
});
Run Code Online (Sandbox Code Playgroud)