<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
$(this).toggleClass('newclass');
});
});
</script>
此函数更改我的表中所选列的类。效果很好。
但是,它不应该允许一次选择超过 2 列(我所说的选择是指切换了新类的列 - newclass)。因此,如果单击其他列,它根本不应该使用react。
我该怎么做?我可以计算当前有多少列使用 newclass,如果是 2,则取消该函数。我不确定如何计算它们,或者这是否是最好的方法。
最佳答案
这是确保不超过 2 个的一种方法
$('#mytable td').click(function() {
var $this = $(this);
// toggle 'on' if
// 1. it doesn't already have the class and
// 2. and there are less than two set to .newclass
// toggle 'off' if
// 1. it already has the class and
// 2. and there are less than two set to .newclass
$this.toggleClass('newclass',
!$this.hasClass('newclass') &&
$('#mytable .newclass').length < 2);
})
关于javascript - jquery - 将toggleClass限制为2个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7933773/