Javascript 如果子级包含活动类,是否打开父级下拉列表?

Javascript 如果子级包含活动类,是否打开父级下拉列表?,javascript,jquery,Javascript,Jquery,我有一个简单的下拉列表,里面有复选框。我在子LI元素上有一个活动类,它模拟一个复选框。我想检查下拉列表是否有具有活动类的子li元素。如果是,我希望在页面加载时自动添加下拉式活动类 这是我的jQuery 我需要从父元素开始定位(此)元素,因为将有多个下拉列表。但是对于这个例子,一个应该是可以的 谢谢你的帮助 $(".advanced-filter").each(function(index) { if($(this).hasClass('active-filter'))

我有一个简单的下拉列表,里面有复选框。我在子LI元素上有一个活动类,它模拟一个复选框。我想检查下拉列表是否有具有活动类的子li元素。如果是,我希望在页面加载时自动添加下拉式活动类

这是我的jQuery 我需要从父元素开始定位(此)元素,因为将有多个下拉列表。但是对于这个例子,一个应该是可以的

谢谢你的帮助

$(".advanced-filter").each(function(index) {
  if($(this).hasClass('active-filter'))
  $(this).parent('ul').addClass('filter-dropdown-active');
});
哦,我应该向上看而不是向下看


干杯。

有两件事让你的代码无法工作

$(".category-filters-area-section").each(function() {
  if ($(this).has(".active-filter").length) {
需要

$(".category-filters-area-section").each(function() {
  if ($(this).has(".active-filter")) {
不带.length as
。has
返回布尔值。你可以用

$(".category-filters-area-section").each(function() {
  if ($(this).find(".active-filter").length) {
下一步:

在这里,
指的是每个
.category filters区域部分
,但在HTML中(在小提琴中),
-section
-list
的父项,因此
.closest()
找不到它,因此这可能是:

    // find the parent and add class ONLY if the "IF" is true
    $(this)
      .find("ul.category-filters-area-list")
      .addClass("filter-dropdown-active");
获取作为.section子级的.list。但是,如果在每个.section中都有多个.list条目(很难说,因为您的小提琴只有1个条目),这将导致问题


或者,您可以找到
li.active
并从那里返回:

  $(".category-filters-area-list li.active-filter")
    .parent()
    .addClass("filter-dropdown-active");

更新的fiddle:

很高兴知道你已经开始工作了,无论如何,你不觉得使用$(this.parent('ul').addClass('filter-dropdown-active');单击子元素而不是循环比在元素上循环更具性能?@AwSnap我希望在页面加载时自动添加下拉式活动类-子元素使用活动类加载,因此设置父活动类:在加载时您不需要。只需将
if
放在选择器内:
$(“.advanced filter.active filter”).parent(“ul”).addClass(…
    // find the parent and add class ONLY if the "IF" is true
    $(this)
      .find("ul.category-filters-area-list")
      .addClass("filter-dropdown-active");
  $(".category-filters-area-list li.active-filter")
    .parent()
    .addClass("filter-dropdown-active");