我有一行div,都有相同的类。它们在页面上显示用户评论。
如果小于4,我写了一个if语句来改变注释的宽度。
有没有办法可以只针对那一行中的那些div,即使它们共享相同的类名
JS
// if statements to sort out widths if there are < 4 comments
if(commentLength === 1){
$('.comment').css('min-width','1453px');
}
else if(commentLength === 2){
$('.comment').css('min-width','700px');
}
else if(commentLength === 3){
$('.comment').css('min-width','470px');
}
HTML
<div class="commentary">
<div class="comment">Sample commnent</div>
<div class="comment">Sample commnent</div>
<div class="comment">Sample commnent</div>
<div class="comment">Sample commnent</div>
</div>
<div class="commentary">
<div class="comment">Sample commnent</div>
<div class="comment">Sample commnent</div>
</div>
<div class="commentary">
<div class="comment">Sample commnent</div>
</div>
答案 0 :(得分:2)
$(".commentary").each(function () {
var $comments = $(this).find('.comment');
var commentLength = $comments.length;
//your JS code goes here, but replace $('.comment') with $comments
});
答案 1 :(得分:0)
$('.commentary').each(function(){
var $myComments = $(this).find('.comment');
var commentLength = $myComments.length;
if(commentLength === 1){
$myComments.css('min-width','1453px');
}
else if(commentLength === 2){
$myComments.css('min-width','700px');
}
else if(commentLength === 3){
$myComments.css('min-width','470px');
}
});