jQuery只选择指定数量的元素

标签 jquery html css onclicklistener

jQuery 仅选择指定数量的元素,选择超过指定数量的元素然后取消选择先前选择的元素。

我有下面的代码来限制第四张图片的选择,但即使选择了三张图片我也需要能够点击,当选择第四张图片时应该取消选择第一张图片。

HTML

<pre>
    <ul class="ul-attribute80" style="margin-top: 10px;">
        <li class="swatchContainer">
            <img id="col-11" src="images/col1.jpg" class="swatch" alt="Skipper" width="30px" height="30px" title="Skipper">
        </li>
        <li class="swatchContainer">
            <img id="col-11" src="images/col1.jpg" class="swatch" alt="Skipper" width="30px" height="30px" title="Skipper">
        </li>
        <li class="swatchContainer">
            <img id="col-11" src="images/col1.jpg" class="swatch" alt="Skipper" width="30px" height="30px" title="Skipper">
        </li>
        <li class="swatchContainer">
            <img id="col-11" src="images/col1.jpg" class="swatch" alt="Skipper" width="30px" height="30px" title="Skipper">
        </li>
    </ul>
</pre>

JS

var counter= 0;
jQuery(".ul-attribute80 li img").click(function() {
    if(counter < 3) {
        if(jQuery(this).hasClass("selected")) {
            jQuery(this).removeClass("selected");
            count--;
        } else {
            jQuery(this).addClass("selected");
            count++;
        }
    }
});

最佳答案

我会使用数组来代替计数器。只需在单击时将元素添加到数组中,检查它们是否已在数组中或数组是否超过三个元素。

var selected = [];
jQuery(".ul-attribute80 li img").click(function () {
    $('.swatch').removeClass("selected");
    if ($.inArray($(this).attr('id'), selected) == -1) {
        selected.push($(this).attr('id'));
    } else {
        selected.splice($.inArray($(this).attr('id'), selected), 1);
    }
    if (selected.length > 3) {
        selected.shift();
    }
    $.each(selected, function () {
        $('#' + this).addClass("selected");
    })
});

jsFiddle example

关于jQuery只选择指定数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25122235/

相关文章:

javascript - 如何从网址中删除#prettyphoto

javascript - Bootstrap 表动态添加行到表和用户然后突出显示并选择一行

css - Autoprefixer 通常会为特定于浏览器的扩展添加前缀

angularjs - 如何更改 uib-accordion-heading 的样式属性

jquery - 通过 jQuery 实现 CSS 选择器性能

javascript - 从数组中获取学生姓名元素具有最高点值并在 jquery 中突出显示此名称

php - 为什么我的表单提交了两次?

javascript - 为什么 jQuery 这里需要 `getWindow(doc)` ?

html - 在不使用 float 的情况下连续对齐div

html - 如何禁用图像上的突出显示