我想限制选择。比如说最多三个。我该怎么做呢?非常感谢帮助。谢谢。
$(function(){
var classHighlight = 'highlight';
var $thumbs = $('.gallery-item').click(function(e) {
e.preventDefault();
//add the class to the currently clicked element (this)
$(this).toggleClass(classHighlight);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="gallery"><!--one ul is going to wrap all li's -->
<li class="gallery-item">
<figure class="img-wrapper fade">
<a class="img-box" href="#">
<img class="center-cropped" alt="gallery image" src="https://placehold.it/180x180.jpg">
</a>
</figure>
</li>
<li class="gallery-item">
<figure class="img-wrapper fade">
<a class="img-box" href="#">
<img class="center-cropped" alt="gallery image" src="https://placehold.it/180x270.jpg">
</a>
</figure>
</li>
<li class="gallery-item">
<figure class="img-wrapper fade">
<a class="img-box" href="#">
<img class="center-cropped" alt="gallery image" src="https://placehold.it/180x180.jpg">
</a>
</figure>
</li>
</ul>
答案 0 :(得分:1)
只需计算已有classHighlight
的人数并采取适当的行动
var classHighlight = 'highlight';
var $thumbs = $('.gallery-item').click(function(e) {
e.preventDefault();
// If less than 3 gallery-items have classHighlight
if($(".gallery-item." + classHighlight).length<3){
//add the class to the currently clicked element (this)
$(this).toggleClass(classHighlight);
}
});
答案 1 :(得分:0)
var li = $( "li" ).slice( 0, 3 )
console.log(li, li.length);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
&#13;
您可以在此处https://api.jquery.com/slice/
尝试使用$.slice(start, end)
更多信息