javascript - jquery - 将toggleClass限制为2个元素

标签 javascript jquery

<script type="text/javascript">
        $(document).ready(function () {
            $('#mytable td').click(function () {
                $(this).toggleClass('newclass');

            });
        });
    </script>

此函数更改我的表中所选列的类。效果很好。

但是,它不应该允许一次选择超过 2 列(我所说的选择是指切换了新类的列 - newclass)。因此,如果单击其他列,它根本不应该使用react。

我该怎么做?我可以计算当前有多少列使用 newclass,如果是 2,则取消该函数。我不确定如何计算它们,或者这是否是最好的方法。

最佳答案

这是确保不超过 2 个的一种方法

jsfiddle

$('#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/

相关文章:

javascript - React-Redux 从 5.x 迁移到 7.x 失败 `connect`

javascript - MongoDB查询集合中对象的数组

javascript - Jquery 图像显示/隐藏不起作用

php - JQuery 隐藏/可见错误

jquery - 如何使用 jQuery 获取下面第 1 个和第 N 个 div 的输入值?

javascript - 单击父项时在菜单中显示/隐藏子项(使用纯 JavaScript)

javascript - FF内的JS显示不同的输出

javascript - 在 Angular View 中获取所有货币过滤器项

jQuery 无需点击即可触发点击事件

javascript - 使用 Jquery 检测选择列表的更改