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");
})
});
关于jQuery只选择指定数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25122235/