Javascript 如果 hasClass 然后将Class添加到父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4208051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:22:39  来源:igfitidea点击:

If hasClass then addClass to parent

javascriptjqueryaddclass

提问by curly_brackets

Original post:Why doesn't this simple script work?

原帖:为什么这个简单的脚本不起作用?

if ($('#navigation > ul > li > ul > li > a').hasClass('.active')) {
    $(this).parent().parent().parent().addClass(".active");
}

EDIT:

编辑:

This won't hide the H1:

这不会隐藏 H1:

if ($('#content h1').hasClass('aktiv')) {
    $(this).hide();
}

Only this will:

只有这样才能:

if ($('#content h1').hasClass('aktiv')) {
    $('#content h1').hide();
}

Why can't I use the (this)?

为什么我不能使用(这个)?

回答by BoltClock

The dot is not part of the class name. It's only used in CSS/jQuery selector notation. Try this instead:

点不是类名的一部分。它仅用于 CSS/jQuery 选择器符号。试试这个:

if ($('#navigation a').hasClass('active')) {
    $(this).parent().addClass('active');
}

If $(this)refers to that anchor, you have to change it to $('#navigation a')as well because the if condition does not have jQuery callback scope.

如果$(this)引用该锚点,您也必须将其更改为$('#navigation a'),因为 if 条件没有 jQuery 回调范围。

回答by Marcus Whybrow

Alternatively you could use:

或者,您可以使用:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}

回答by Bill Criswell

You can't use $(this)since jQuery doesn't know what it is there. You seem to be overcomplicating things. You can do $('#content h1.aktiv').hide(). There's no reason to test to see if the class exists.

您不能使用,$(this)因为 jQuery 不知道它在那里。你似乎把事情复杂化了。你可以做到$('#content h1.aktiv').hide()。没有理由测试该类是否存在。

回答by Marcus Whybrow

The reason that does not work is because thishas no specific meaning inside of an if statement, you will have to go back to a level of scope where thisis defined (a function).

不起作用的原因是因为thisif 语句内部没有特定含义,您将不得不返回到this定义(函数)的范围级别。

For example:

例如:

$('#element1').click(function() {
    console.log($(this).attr('id')); // logs "element1"

    if ($('#element2').hasClass('class')) {
        console.log($(this).attr('id')); // still logs "element1"
    }
});

回答by Edgar Quintero

If anyone is using WordPress, you can use something like:

如果有人在使用 WordPress,您可以使用以下内容:

if (jQuery('.dropdown-menu li').hasClass('active')) {
    jQuery('.current-menu-parent').addClass('current-menu-item');
}

回答by SLaks

You probably want to change the condition to if ($(this).hasClass('active'))

您可能希望将条件更改为 if ($(this).hasClass('active'))

Also, hasClassand addClasstake classnames, not selectors.
Therefore, you shouldn't include a ..

此外,hasClassaddClass采用classnames,而不是选择器。
因此,您不应包含..