【问题标题】:Wrong jQuery(this) result in a jQuery().parents() foreach loop错误的 jQuery(this) 导致 jQuery().parents() foreach 循环
【发布时间】:2013-08-03 12:34:59
【问题描述】:

我有以下嵌套的<ul> <li> 菜单结构:

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

我想选择类型为&lt;ul&gt; 的所有Category 的2.1 父级,直到到达根ul。所以我的代码如下: 网址: localhost:22342/Home/Products/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.
        }

问题: 蓝色背景应用于用 * 制作的部分,但我希望用 # 标记这些部分。

【问题讨论】:

    标签: jquery accordion parent css-selectors nested-lists


    【解决方案1】:

    你的电话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(),它将仅返回与选择器匹配的第一个元素

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多