2016-02-15 28 views
1

我有這樣的複選框的列表:檢查一個複選框被選中,並應用樣式父元素與jQuery

<ul class="cate_select_ul"> 
    <li> 
     <!-- outer checkbox A --> 
     <label><input value="251" type="checkbox" name="post_category[]">Automobiles &amp; Transport</label> 
     <ul class="children"> 
      <li> 
       <!-- inner checkbox A --> 
       <label><input value="252" type="checkbox" name="post_category[]">Car Parts</label> 
      </li> 
     </ul> 
    </li> 
    <li> 
     <!-- outer checkbox B --> 
     <label><input value="251" type="checkbox" name="post_category[]">Automobiles &amp; Transport</label> 
     <ul class="children"> 
      <li> 
       <!-- inner checkbox B --> 
       <label><input value="252" type="checkbox" name="post_category[]">Car Parts</label> 
      </li> 
     </ul> 
    </li> 

</ul> 

我要檢查如果內複選框被選中與否。如果是這樣,我想更改父外部複選框周圍標籤的樣式。 我試過,但它不能正常工作:

if($('ul.children input[name="post_category[]"]:checked').length > 0){ 
$("this").parent().parent().parent().parent().children("label").css({"color":"red"}); 
} 

如何使這項工作任何想法?

+0

你把你的代碼片段放在哪裏?你應該確定你可以從$(this)得到什麼。 – Sky

回答

3

您的示例不起作用,因爲$("this")嘗試選擇標籤類型爲<this>的元素。由於該元素不存在,因此不會選擇任何內容。

通常情況下,$("this")$(this)(因爲this is a keyword而不是一個字符串),但在你的情況下,並不是指你認爲它,因爲它看起來不像有任何範圍的元素。在你的情況下,變量this可能是指window對象;您隨時可以使用console.log(this)進行檢查。


作爲一種解決方案,你在爲了使用.each() methodthis來指代當前檢查input元件可以遍歷的元素。你也不必鏈.parent()方法四倍,因爲你可以使用.closest() method爲了選擇指定的最近的祖先:

Example Here

$('ul.children input[name="post_category[]"]:checked').each(function() { 
    $(this).closest('.children').prev('label').css('color', '#f00'); 
}); 

當然,你實際上並不需要使用.each()方法,因爲您可以直接選擇元素。

在下面的行中,在:has() selector順序用於選擇已經檢查input[name="post_category[]"]後代元素ul.children元件。從那裏,以前label元素被選中和相應的CSS改變:

Example Here

$('ul.children:has(input[name="post_category[]"]:checked)').prev('label').css('color', '#f00'); 

作爲一個側面說明,如果你想要把這個在change事件監聽器,它會是這個樣子:

Updated Example

$('ul.children input[name="post_category[]"]').on('change', function() { 
    $(this).closest('.children').prev('label').toggleClass('selected', this.checked); 
}); 
+1

這不僅是一個正確的答案。我能夠學到這麼多東西!非常感謝你!!! – mesqueeb

+0

親愛的喬希,當我試圖通過「不」來更改「有」,以僅填充空的兒童複選框列表的標籤時,所有外層標籤變爲紅色。 = S任何提示? – mesqueeb

+0

@mesqueeb然後我很確定你想''not()''在':has()'''''''''ul.children:not(:has(...))''''''周圍。所以它會是'$('ul.children:not(:has(input [name =「post_category []」]:checked))')。prev('label').css('color','#f00 ');' - > [更新示例](https://jsfiddle.net/j7g2L02t/)。 –

相關問題