为什么这个 jquery 函数不能与多个 if 语句一起使用?

问题描述 投票:0回答:1

只要其他 if 语句不存在,以下每个 if 语句都可以完美运行。我不明白为什么同时使用两个 if 语句会导致该函数无法工作。我尝试了很多变体,但无法弄清楚。这是代码:

$("a").click(function(event){   
    event.preventDefault();
    let lItem = document.querySelectorAll(".listing-item");
    let mItem = document.querySelectorAll(".menu-item");    
    let destination = $(this).attr("href");

    if ( $(this).parent(lItem) )  {
        tlUp.tweenTo(0, {
            onComplete: () => {
                window.location = destination;
            }
        });
    }

    if ( $(this).parent(mItem) ) {
        tlMenu.tweenTo(0, {
            onComplete: () => {
                window.location = destination;
            }
        });
    }
});
javascript jquery gsap
1个回答
0
投票

jQuery

.parent()
方法需要一个字符串或什么都不作为参数,您传递的是
NodeList
的实例,这相当于不传递任何内容。因此,您的两个条件都是正确的,因为
$(this)
始终有一个父级(因为它不是文档根)。

如果要检查元素的父元素是否属于由

lItem
mItem
定义的某些组,则应使用不同的方法。正确的方法是使用 jQuery 的
.closest()
方法,该方法接受字符串选择器并遍历 DOM 以查找与提供的选择器匹配的第一个祖先。

例如:

if ($(this).closest('.listing-item').length > 0) {
    // one ancestor belongs to the 'listing-item' class
}
if ($(this).closest('.menu-item').length > 0) {
    // one ancestor belongs to the 'menu-item' class
}

或者,如果您想检查元素父级是否具有该特定类,您可以使用以下形式:

if ($(this).parent().is('.listing-item')) {
    // the parent belongs to the 'listing-item' class
}
if ($(this).parent().is('.menu-item')) {
    // the parent belongs to the 'menu-item' class
}

在最后一个示例中,

.parent()
用于选择当前元素的直接父元素,然后
.is(...)
用于检查该父元素是否具有该特定类。

© www.soinside.com 2019 - 2024. All rights reserved.