2017-06-28 40 views
-3

我想限制選擇。比方說,最多三個。我該怎麼做呢?幫助將非常感激。謝謝。用jquery選擇最多10個li物品

$(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

你能解釋一下你需要的嗎? –

+0

你的標題是「最多10個」,你的問題是「最多3個」? – Mark

+0

[使用jQuery選擇第一個「n」項目的可能的重複項)(https://stackoverflow.com/questions/1865552/selecting-the-first-n-items-with-jquery) – Kaddath

回答

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); 
    } 
}); 
0

var li = $("li").slice(0, 3) 
 
console.log(li, li.length);
<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>

您可以在這裏$.slice(start, end)更多信息嘗試https://api.jquery.com/slice/