【问题标题】:Switch color of button on click (and revert color of other buttons without deselecting all the buttons on the page)单击时切换按钮的颜色(并在不取消选择页面上所有按钮的情况下恢复其他按钮的颜色)
【发布时间】:2018-10-13 03:58:12
【问题描述】:

我有许多按钮分为不同的面板,我想在 jquery 中单击按钮时更改按钮的颜色。我无法使用本次讨论中的解决方案:Changing the Color of button on Click in bootstrap

$("button").click(function({$("button").removeClass("active");$(this).addClass("active");});

因为我必须为每个面板选择一个按钮,并且使用此解决方案,当我单击该按钮时,它也会取消选择其他面板的按钮。

【问题讨论】:

  • 你能提供更多代码吗?参考minimal reproducible example
  • 听起来你的问题与$("button").removeClass("active")有关。正如@Alex Wu 解释的那样,这会影响所有按钮,而不仅仅是您单击的那个。

标签: javascript jquery asp.net asp.net-ajax


【解决方案1】:

你的代码在做什么

$("button").click(function({
  // this removes the "active" class from all buttons
  $("button").removeClass("active");
  $(this).addClass("active");
});

$("button") 选择所有按钮。

建议:

这将“选择”每个被点击的按钮

$("button").click(function({
  $(this).addClass("active");
});

如果您希望单击“选择”按钮,然后再次单击“取消选择”按钮

$("button").click(function({
  $(this).toggleClass("active");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多