【问题标题】: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?将单击事件绑定到多个按钮时,如何使单击的按钮做一件事,而所有其他按钮做另一件事?
【发布时间】:2015-05-19 14:04:03
【问题描述】:

我在 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');
});

它不工作。我的想法是,在单击的按钮变为红色之前,将所有按钮变为蓝色,但我不知道该怎么做。我对第三行的想法是找到最接近的具有.ui-grid-b 类的 div,将它们全部变为蓝色,然后将我单击的那个变为红色。

我知道一种方法是将每个按钮单独设置为蓝色,然后单击为红色,但如果有 100 个按钮,我希望它能够工作,并且我不想手动编码每一行。

有什么想法吗?

【问题讨论】:

    标签: javascript jquery html css jquery-mobile


    【解决方案1】:

    你需要使用:

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

    Working Demo

    【讨论】:

    • 和你的差不多! :D :)
    【解决方案2】:

    试试这个:您可以将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

    【讨论】:

    • 太完美了!非常感谢!
    【解决方案3】:

    blue 添加到所有人。将red 专门添加到单击的按钮。

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

    注意 - 不确定代码的性能如何。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      相关资源
      最近更新 更多