使用jQuery更改父元素样式

Change parent element style with jQuery

本文关键字:元素 样式 jQuery 使用      更新时间:2023-09-26

我有下一个html设置:

<div class="one">
    <div class="two">
        <a href="#" class="three">Click</a>
    </div>
</div>

当我用jQuery点击元素.three时,我想更改类为.one的元素的背景色。

这就是我试图使用的:

$(function(){
    $('.three')(function(){
        $(this).parent().parent().css('backgroundColor', 'red');
    })
});

下面是一个小提琴的例子:https://jsfiddle.net/Munja/a7unbs2p/

我在SO上搜索解决方案,但找不到足够快的速度(可能我看起来不够好:/)。

谢谢。

您需要使用.click().on('click')。。你也可以使用.closest(),而不是使用parent()两次

$(function(){
    $('.three').on('click',function(){
        $(this).closest('.one').css('backgroundColor', 'red');
    })
});

只需在代码中添加Click事件。首先添加jquery.min.js,然后添加脚本。你可以这样做-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
     $(".three").click(function(){
         $(this).parent().parent().css("background","red");
     });
</script>

由于它是元素的descedant,所以可以使用.parents(),它会向上移动,直到找到选择器。

此外,您可以在CSS方法中使用CSS语法(background-color而不是backgroundColor)。

$('.three').on('click', function(){
    $(this).parents('.one').css('background-color', 'red');
})

我不能发表评论,所以,除了更高的答案之外,还有一点:

$(function(){
    $('.three').on('click',function(){
        $(this).closest('.one').css('background-color', 'red');
    })
});

Css没有名为backgroundColor 的属性

您可以使用这样的东西。

$('.three').on('click',function(){
    $(this).closest('.one').css('backgroundColor', 'red');
})