2014-10-31 59 views
0

總之,我試圖抓住基於ID的項目的子集合。我試圖抓取1-1, 1-1-0, 1-1-1但不是1-19, 1-19-0, 1-19-1。有什麼辦法可以做到這一點?CSS選擇器允許一件事但不是另一件事?

$(function(){ 
 
    
 
    // grabs all items but only want 1-1 items. 
 
    $('[data-parent-id^=1-1]').prop('checked',true); 
 
    
 
    // does not grab the first item 1-1. 
 
    $('[data-parent-id^=1-2-]').prop('checked',true);  
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<div> 
 
<input type="checkbox" data-parent-id="1-1"> 
 
<input type="checkbox" data-parent-id="1-1-0"> 
 
<input type="checkbox" data-parent-id="1-1-1">  
 
<input type="checkbox" data-parent-id="1-19"> 
 
<input type="checkbox" data-parent-id="1-19-0"> 
 
<input type="checkbox" data-parent-id="1-19-1"> 
 
    </div> 
 
<div> 
 
    <input type="checkbox" data-parent-id="1-2"> 
 
<input type="checkbox" data-parent-id="1-2-0"> 
 
<input type="checkbox" data-parent-id="1-2-1">  
 
<input type="checkbox" data-parent-id="1-29"> 
 
<input type="checkbox" data-parent-id="1-29-0"> 
 
<input type="checkbox" data-parent-id="1-29-1"> 
 
    </div>

回答

3

如果我正確理解你的問題,這將這樣的伎倆:

$('[data-parent-id="1-1"], [data-parent-id^="1-1-"]').prop('checked',true); 

說明:選擇的第一部分恰好獲得1-1,第二部分得到什麼從1-1-開始。

+1

剛掛上它,它的工作流暢如黃油!謝謝! – Tony 2014-10-31 21:17:21

-1

這裏做,使用:not選擇的一種方式:

$('[data-parent-id^=1-1]:not([data-parent-id^=1-19])').prop('checked',true); 

其中:

  • [data-parent-id^=1-1]比賽的所有屬性開始1-1
    • 1-1
    • 1-1-0
    • 1-1-1
    • 1-19
    • 1-19-0
    • 1-19-1
  • :not([data-parent-id^=1-19])排除所有的屬性開始1-19
    • 1-19
    • 1-19-0
    • 1-19-1
1

我認爲Mooseman解決方案是最簡單的一種。您也可以使用正則表達式並更精確地過濾元素:http://jsfiddle.net/6hfryod2/

$(function(){ 
    $("div > input[type='checkbox']").filter(function(index) { 
     return /^(1-1)$|^(1-1-)/gi.test($(this).attr("data-parent-id")); 
    }).prop("checked", true); 
});