1

我有一排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>
4

2 回答 2

2
$(".commentary").each(function () {
   var $comments = $(this).find('.comment');
   var commentLength = $comments.length;

   //your JS code goes here, but replace $('.comment') with $comments
});

小提琴:http: //jsfiddle.net/jG6FB/

于 2013-01-17T03:32:51.623 回答
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');
    }        
});
于 2013-01-17T03:32:55.887 回答