我想知道如何使用Jquery选择thumbSlider下的元素
<div class="thumbSlider">
<div class="graythumb showthumb">
<div class="bluethumb">
</div>
我熟悉如何选择一个类(class)做
$(function () {
if ($('.graythumb').hasClass('showthumb')) {
alert('has class2');
}
});
但我需要确保我只会选择 thumbSlider 类下的元素
在 css 中是这样的
.thumbSlider .graythumb { display:none;}
.thumbSlider .graythumb .showthumb { display:block;}
最佳答案
好吧,就像在 CSS 中一样:
$(".thumbSlider .graythumb") // Child
$(".thumbSlider > .graythumb") // Immediate child
或使用.find()
$(".thumbSlider").find(".graythumb")
在使用库时,请务必花一些时间了解它们的 API:
https://api.jquery.com/
https://api.jquery.com/category/selectors/
在你的情况下看起来像:
if ( $(".thumbSlider .graythumb").hasClass('showthumb')) {
// or
if ( $(".thumbSlider").find(".graythumb").hasClass('showthumb')) {
或者如果您想确保它仅适用于直系子级:
if ( $(".thumbSlider > .graythumb").hasClass('showthumb')) {
// or
if ( $(".thumbSlider").children(".graythumb").hasClass('showthumb')) {
// or
if ( $(".thumbSlider").find("> .graythumb").hasClass('showthumb')) {
关于javascript - 选择类选择器子div Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48607345/