jQuery 将Class添加到父级(LI)

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

addClass to parent(LI)

jqueryaddclass

提问by Sergio

I have an element "A", when I click on it, I want to change parent element's (LI) class to selected, but nothing changes...

我有一个元素“A”,当我点击它时,我想将父元素的 ( LI) 类selected更改为,但没有任何改变......

$(".filters-list li a").click(function () {
    $(".filters-list li").removeClass("selected");
    $(this).parent('li').addClass('selected'); // I also tried .parent().addClass
});

Then I tried this code:

然后我尝试了这个代码:

$(".filters-list li a").click(function () {
    $(".filters-list li").removeClass("selected");
    $(this).parent().get(0).addClass('selected'); // IE reports something like this: Object doesn't support addClass...
});

When I tried to define LIwith this code, it just reported me [Object HTMLLIElement]:

当我尝试LI使用此代码进行定义时,它只是报告了我[Object HTMLLIElement]

alert($(this).parent().get(0));

What I'm doing wrong?

我做错了什么?

回答by Sergio

Try

尝试

$(".filters-list li a").click(function (e) {
    e.preventDefault();
    $(".filters-list li").removeClass("selected");
    $(this).closest('li').addClass('selected'); // I also tried .parent().addClass
});

.closest()will get the first element that matches the selector.

.closest()将获得与选择器匹配的第一个元素。

回答by Hugo Tostes

I made a sample for you:

我为你做了一个样本:

<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
    <style>
        .selected {font-weight:bold}
    </style>
    <ul class="filters-list">
        <li class="selected"><a href="#section1">About</a></li>
        <li><a href="#section2">Gallery Photos</a></li>
        <li><a href="#section3">Contact</a></li>
    </ul>

<script type="text/javascript">
$(document).ready(function(){
    $(document).on("click",".filters-list li a", function () {
        $(".filters-list li").removeClass("selected");
        $(this).parent().addClass("selected");
    });
});
</script>

回答by user1825286

Try this out:

试试这个:

$(this).parents("li:first").addClass('selected');

it could be that you are not selecting the target parent

可能是您没有选择目标父级