我试图给一个元素(.item)一个基于子类的类 - 但是我想把它保存到目标容器中。下面你可以看到我正在尝试的脚本 - 这为我的所有元素提供了类.left基于.item类的额外类。我只希望这发生在实际拥有此类的容器中。我该怎么做呢?
HTML:
<div class="container"><!-- give class -->
<div class="item itemonlypicture"> </div>
<div class="left"> </div>
</div>
<div class="container">
<div class="item"> </div>
<div class="left"> </div>
</div>
<div class="container">
<div class="item "> </div>
<div class="left"> </div>
</div>
脚本:
$(document).ready(function () {
if($(".item").hasClass("itemonlypicture")) {
$(".container").addClass("image");
}
});
答案 0 :(得分:2)
使用closest
获取与传递的选择器匹配的第一个祖先。
$('.itemonlypicture').closest('.container').addClass('myClass');
$('.itemonlypicture').closest('.container').addClass('myClass');
&#13;
.myClass {
color: green;
font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="item itemonlypicture">1</div>
<div class="left">2</div>
</div>
<div class="container">
<div class="item">3</div>
<div class="left">4</div>
</div>
<div class="container">
<div class="item ">5</div>
<div class="left">6</div>
</div>
&#13;
答案 1 :(得分:0)
尝试以下JS
$(document).ready(function() {
$('.item').each(function(){
if($(this).hasClass("itemonlypicture"))
{
$(this).closest(".container").addClass("image");
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div> <--- give class
<div class="item itemonlypicture"> </div>
<div class="left"> </div>
</div>
</div>
<div class="container">
<div class="item"> </div>
<div class="left"> </div>
</div>
<div class="container">
<div class="item "> </div>
<div class="left"> </div>
</div>
&#13;