gpt4 book ai didi

javascript - 如果第一个 child 有类,如何设置元素的样式?

转载 作者:太空狗 更新时间:2023-10-29 15:33:55 26 4
gpt4 key购买 nike

我有2个.school,几个.class-room,里面还有一些.my-child

如果 .my-child 位于学校的第一个 .class-room 中,我想为该学校设置黄色背景的样式。但它没有按预期显示。

jsfiddle

$('.school').each(function() {
$(this).find('.my-child').each(function(i, el) {
$(this).addClass('child' + (i + 1));
});
if ($('.school .class-room:first-child').children().hasClass('.my-child')) {
$('.school').css('background', 'yellow');
}
})
.my-child.child1 {
background: red;
}

.my-child.child2 {
background: green;
}

.my-child.child3 {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="school">
<div class="class-room">
<div class="my-child">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="my-child">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="my-child">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
</div>

<br><br>

<div class="school">
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="my-child">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="my-child">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
<div class="class-room">
<div class="my-child">Child</div>
</div>
<div class="class-room">
<div class="other">Child</div>
</div>
</div>

最佳答案

你不能在 hasClass 中使用点:

改变:

.hasClass('.my-child')

到:

.hasClass('my-child')

我还会在您的条件中使用 $(this) 来仅选择正确的学校来更改背景颜色:

if ( $(this).children('.class-room:first-child').children().hasClass('my-child') )

https://jsfiddle.net/5wxaoj1m/

编辑:更新以解决评论中的问题,我添加了一个 jsfiddle 链接。

关于javascript - 如果第一个 child 有类,如何设置元素的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55976659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com