jQuery按钮更改类

时间:2018-03-21 13:03:33

标签: javascript jquery html

我编写了以下代码,当您点击按钮时,整个样式将被更改。

$(".Button1").click(function() {
  $(this).toggleClass('Button1Changed');
});
.Button1 {
  background-color:#000000;
  color:#ffffff;
}

.Button1Changed {
  background-color:#ff0000;
  color:#ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="Button1">Button 1 - Click</button>

但现在我需要添加一些新按钮,如下面的代码。我希望当我点击“按钮2”时,“按钮1”的样式再次变为第一堂课!或者当我点击“按钮3”时,按钮2的样式再次改变&amp; ...

我该怎么做?!

$(".Button1").click(function() {
  $(this).toggleClass('Button1Changed');
});
.Button1 {
  background-color:#000000;
  color:#ffffff;
}

.Button1Changed {
  background-color:#ff0000;
  color:#ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="Button1">Button 1 - Click</button>
<button class="Button1">Button 2 - Click</button>
<button class="Button1">Button 3 - Click</button>
<button class="Button1">Button 4 - Click</button>

2 个答案:

答案 0 :(得分:1)

您可以使用.not()方法排除当前元素,例如this,并从其他元素中排除.removeClass()

  $(".Button1").not(this).removeClass('Button1Changed'); 

&#13;
&#13;
$(".Button1").click(function() {
  $(".Button1").not(this).removeClass('Button1Changed');
  $(this).toggleClass('Button1Changed');
});
&#13;
.Button1 {
  background-color: #000000;
  color: #ffffff;
}

.Button1Changed {
  background-color: #ff0000;
  color: #ffffff;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="Button1">Button 1 - Click</button>
<button class="Button1">Button 2 - Click</button>
<button class="Button1">Button 3 - Click</button>
<button class="Button1">Button 4 - Click</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

另一种方法可以基于.add():切换当前元素的类和最后更改的按钮:

$('.Button1.Button1Changed').add(this).toggleClass('Button1Changed');

$(".Button1").on('click', function(e) {
  $('.Button1.Button1Changed').add(this).toggleClass('Button1Changed');
});
.Button1 {
    background-color: #000000;
    color: #ffffff;
}

.Button1Changed {
    background-color: #ff0000;
    color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="Button1">Button 1 - Click</button>
<button class="Button1">Button 2 - Click</button>
<button class="Button1">Button 3 - Click</button>
<button class="Button1">Button 4 - Click</button>