javascript - 两个按钮像单选按钮一样改变类,但一次只有一个

标签 javascript jquery html css jquery-selectors

$('#axe, #saw').click(function(e) {
  var id = $(this).attr('id');
  if (id == 'axe') {
    $(this).toggleClass('as-in-one as-one');
  } else if (id == 'saw') {
    $(this).toggleClass('as-in-two as-two');
  }

})
.as-in-one {
  color: red;
}

.as-one {
  color: blue;
}

.as-in-two {
  color: red;
}

.as-two {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='axe' class='axe as-in-one'>AXE</button>
<button id='saw' class='saw as-in-two'>SAW</button>

在我的代码中,我只想更改一个按钮的类,从 redblue,但是如果我点击另一个按钮,第一个按钮会变如果它是 blue,则为默认类 red,另一个切换为 blue,反之亦然。

最佳答案

也许不是我想做的 - 但你去吧!当axe单击,添加 as-in-two类并删除 as-two上课,什么时候saw单击,添加 as-in-one类并删除 as-one类。

请看下面的演示:

$('#axe, #saw').click(function(e) {
  var id = $(this).attr('id');
  if (id == 'axe') {
    $(this).toggleClass('as-in-one as-one');
    $('#saw').addClass('as-in-two');
    $('#saw').removeClass('as-two');
  } else if (id == 'saw') {
    $(this).toggleClass('as-in-two as-two');
    $('#axe').addClass('as-in-one');
    $('#axe').removeClass('as-one');
  }

})
.as-in-one {
  color: red;
}

.as-one {
  color: blue;
}

.as-in-two {
  color: red;
}

.as-two {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='axe' class='axe as-in-one'>AXE</button>
<button id='saw' class='saw as-in-two'>SAW</button>

最好使用单个 redblue类:

$('.as-in-one').click(function(e) {
   $('.as-in-one').not(this).removeClass('as-one');
   $(this).toggleClass('as-one');
})
.as-in-one {
  color: red;
}
.as-in-one.as-one {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='axe' class='as-in-one'>AXE</button>
<button id='saw' class='as-in-one'>SAW</button>

关于javascript - 两个按钮像单选按钮一样改变类,但一次只有一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45551985/

相关文章:

javascript - ngOptions 创造奇怪的值(value)结果

javascript - 将文本应用于图像(不推送它)

jquery - 处理 ajax 请求中 session 超时的最佳方法是什么?

javascript - 使用 HTML 和 Jquery 创建网格,而不使用插件

html - 复选框取消选择动画

html - 使用 Emacs 将纯文本文件转换为 HTML。如何添加结束标签?

javascript - 检查 node.js 中的实际文件类型

javascript - Firestore没有执行操作的权限

javascript - 通过防止窗口事件问题防止双重提交

python - 如何使用 Flask 将二维数组中的表格从 Python 渲染为 HTML?