我在下面的代码添加了一个“禁用”类,并在选择了 3 个列表元素时尝试单击第 4 个元素时发出警报。
我希望在选择/单击第 3 个元素时添加类,而不是在尝试选择第 4 个元素时添加类。当然,我仍然希望在尝试选择超过 3 个元素时显示警报。
我怎样才能做到这一点?
<script type="text/javascript">
jQuery(function ($) {
$(document).on('mousedown', 'ul.image_picker_selector li', function (evt) {
evt.preventDefault();
evt.stopPropagation();
// get the number of items already selected:
var ctSelected = $(this).siblings('.selected').length;
if (ctSelected === 3) {
$(this).closest('.image_picker_selector').find('li:not(.selected)').addClass('disabled');
alert('You have already selected 3 items!' + ('\n') + 'You can undo a selection.');
} else {
$(this).toggleClass('selected');
}
if (ctSelected < 3) {
$(this).closest('.image_picker_selector').find('li:not(.selected)').removeClass('disabled');
}
});
})
</script>
<ul class="thumbnails image_picker_selector">
<li>
<div class="thumbnail required">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q4-1.jpg"></div>
</li>
<li>
<div class="thumbnail selected required">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q4-2.jpg">
</div>
</li>
<li>
<div class="thumbnail selected required">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q4-3.jpg">
</div>
</li>
<li class="selected">
<div class="thumbnail selected required">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q4-4.jpg">
</div>
</li>
<li><div class="thumbnail required">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q4-5.jpg"></div>
</li>
</ul>