2013-08-02 46 views
0

我有以下嵌套<ul> <li>菜單結構:錯誤的jQuery(這)結果在一個jQuery()家長()foreach循環

<ul class="tree-0"> 
* #<li> 
     <a> Root Category </a> 
     <ul class="tree-1"> 
*  <li> 
      <a href="/Home/Products/1">Category 1</a> 
      <ul class="tree-2"> 
*    <li><a href="/Home/Products/11">SubCategory 1.1</a></li> 
*    <li><a href="/Home/Products/12">SubCategory 1.2</a></li> 
      </ul> 
     </li> 
    #  <li> 
      <a href="/Home/Products/2">Category 2</a> 
      <ul class="tree-2"> 
* #   <li><a href="/Home/Products/21">Category 2.1</a></li> 
       <li><a href="/Home/Products/22">Category 2.2</a></li> 
      </ul> 
     </li> 
     </ul> 
    </li> 
</ul> 

我想選擇所有類別的2.1父母<ul>型的,直到到達根ul。所以我的代碼如下: 網址:本地主機:22342/Home /產品/ 21

//Get the `<a>` tag which has the href equal to the pathname 
var a = jQuery("a[href='" + window.location.pathname + "']"); //Suppose its Category 2.2 

//Get ul parents of <a> 
var parents = jQuery(a).parents("ul"); 

//Loop through the parents array() 
for (var i = 0; i < parents.length; i++) { 
      console.log(jQuery(parents[i]).attr("level")); // check if looping occurs till root 
      jQuery(parents[i]).find("li:first").css("background","blue"); // apply a class to first child of the parent element. 
     } 

的問題: 藍色背景適用於帶* maked的部分,但是我希望用#標記部分。

回答

2

您的通話var parents = jQuery(a).parents("ul");應該var parents = jQuery(a).closest("ul");

當你說var parents = jQuery(a).parents("ul");它取它們的目標a的祖先在這種情況下,有兩個祖先ul元素都ul元素,那麼它適用的CSS在第一li每個ul元素

如果使用.closest()它將只返回返回的第一個元素選擇匹配