0

我在下面的代码添加了一个“禁用”类,并在选择了 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>
4

1 回答 1

0

您可以通过简单地将toggleClass()函数移动到长度计算和比较上方来实现这一点。

<script type="text/javascript">
jQuery(function($){

    $(document).on('mousedown', 'ul.image_picker_selector li', function(evt) {
        evt.preventDefault();
        evt.stopPropagation();

        // Do nothing if we are disabled
        if(  $(this).hasClass("disabled") ) return false;

        $(this).toggleClass('selected');

        // get the number of items already selected:
        var ctSelected = $(this).closest('.image_picker_selector').find('.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 if ( ctSelected == 3) {
            $(this).closest('.image_picker_selector').find('li:not(.selected)').addClass('disabled');
        } else {
            $(this).closest('.image_picker_selector').find('li:not(.selected)').removeClass('disabled');
        } 

    });
});
</script>

这是一个工作小提琴:http: //jsfiddle.net/jNLJG/1/

于 2013-05-22T19:00:16.290 回答