Javascript JQuery 将类添加到父元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3482543/
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 04:50:41  来源:igfitidea点击:

JQuery add class to parent element

javascriptjquery

提问by Alex Sleiborg

I have to set a class name on a (li) element. This script find all the (a) elements in the list, and creates a click event.

我必须在 (li) 元素上设置一个类名。此脚本查找列表中的所有 (a) 元素,并创建一个单击事件。

jQuery("#" + ElementID).find(TagName).click(function () {

    GetPageByUrl(jQuery(this).attr("href"));
    jQuery(this).parent().addClass('yourClass');
    //ChangeSelectedMenuItem(this);
    return false;
});

The parent of every (a) element is a (li) element

每个 (a) 元素的父元素都是一个 (li) 元素

But nothing happens when this line is executing jQuery(this).parent().addClass('yourClass');

但是当这一行正在执行 jQuery(this).parent().addClass('yourClass'); 时什么也没有发生。

Everything else is working just fine.

其他一切都工作得很好。

What am I doing wrong here?

我在这里做错了什么?



Okay, but it still won't work. It won't add any class jQuery(this).addClass('yourClass'); Should add a class to the (a) element, but it doesn't?

好吧,但它仍然不起作用。它不会添加任何类 jQuery(this).addClass('yourClass'); 应该向 (a) 元素添加一个类,但它没有?

回答by Sarfraz

Specify the optional selector to target what you want:

指定可选选择器以定位您想要的内容:

jQuery(this).parent('li').addClass('yourClass');

Or:

或者:

jQuery(this).parents('li').addClass('yourClass');

回答by Delan Azabani

$(this.parentNode).addClass('newClass');