将单个单击事件绑定到多个按钮时,如何使单击的按钮做一件事而所有其他按钮做另一件事?

When binding a single click event to multiple buttons, how can I make the clicked button do one thing and all the other buttons do another?

我在 ui-grid-b

中有三个按钮
<div class="ui-grid-b">
    <div class="ui-block-a"><button id="btnOvenA" style="width:100%" value="a">A</button></div>
    <div class="ui-block-b"><button id="btnOvenB" style="width:100%" value="b">B</button></div>
    <div class="ui-block-c"><button id="btnOvenC" style="width:100%" value="c">C</button></div>
</div>

每当单击一个按钮时,我想将其文本变为红色。我想把其他文字变成蓝色。我的点击事件目前看起来像这样:

$("#btnOvenA, #btnOvenB, #btnOvenC").click(function (event) {
   oven += $(event.target).attr('value');
   $(this).closest('div .ui-grid-b').css('color', 'blue');
   $(this).css('color', 'red');
});

它不起作用。我的想法是,在单击的按钮变为红色之前,将所有按钮变为蓝色,但我不确定该怎么做。第三行我的想法是找到最接近的div和class.ui-grid-b,把它们都变成蓝色,然后把我点的变成红色就好了。

我知道一种方法是在dividually 中将每个按钮设置为蓝色,然后单击为红色,但如果有 100 个按钮,我希望它能正常工作,但我不想让对每一行进行手写。

有什么想法吗?

您需要使用:

$(".ui-grid-b button").click(function (event) {
  $(".ui-grid-b button").not(this).css('color', 'blue');
  $(this).css('color', 'red');
});

Working Demo

试试这个:您可以将 ui-grid-b div 中的所有按钮设为蓝色,并将单击的按钮设为红色

$("#btnOvenA, #btnOvenB, #btnOvenC").click(function (event) {
   oven += $(event.target).attr('value');
   //make all button blue first
   $(this).closest('div.ui-grid-b').find('button').css('color', 'blue');
   //make clicked button red
   $(this).css('color', 'red');
});

JSFiddle Demo

全部加blue。将 red 专门添加到单击的按钮。

$("#btnOvenA, #btnOvenB, #btnOvenC").click(function (event) {
    $("[id^=btnOven]").not(this).css("color","blue");
    $(this).css("color","red");
});

注意 - 不确定代码的执行情况。

FIDDLE - http://jsfiddle.net/w0gqo6hs/