如果前一个div没有相同的类属性,则检查每个div

时间:2015-12-31 03:07:41

标签: javascript css

所以我的代码看起来像这样:(随机生成)

<div class="class1"> </div>
<div class="class2"> </div>
<div class="class1"> </div>
<div class="class1"> </div>
<div class="class2"> </div>
<div class="class1"> </div>
<div class="class1"> </div>
<div class="class1"> </div>
<div class="class2"> </div>

现在我想检查每个div是否前一个div没有相同的类属性

我想实现这样的目标:

<div class="class1"> </div> <!-- first div: nothing happens-->
<div class="class2"> </div> <!-- previous div has other class: margin-top:10px;-->
<div class="class1"> </div> <!-- previous div has other class: margin-top:10px;-->
<div class="class1"> </div> <!-- same class: nothing happens-->
<div class="class2"> </div> <!-- previous div has other class: margin-top:10px;-->
<div class="class1"> </div> <!-- previous div has other class: margin-top:10px;-->
<div class="class1"> </div> <!-- same class: nothing happens-->
<div class="class1"> </div> <!-- same class: nothing happens-->
<div class="class2"> </div> <!-- previous div has other class: margin-top:10px;-->

我想我需要循环每一个div并检查前一个div是否具有相同的类或类似的东西

我真的希望现在更好理解。 :)

3 个答案:

答案 0 :(得分:1)

我认为以下应该有效。保持对上一课程的引用。迭代以^=开头的所有div,检查prev类是否与我们循环的元素的类匹配,然后应用我们的margin top。最后,将前一个类设置为当前元素的类,以便在下一次迭代时进行比较。

var prev_class;

$('div[class^="class"]').each(function(){
    var $this = $(this);

    if(prev_class == $this.prop('class')){
        $this.css('margin-top', '10px');
    }

    prev_class = $this.prop('class');
});

答案 1 :(得分:1)

使用jquery的next()和prev()以及hasClass(),您可以看到类差异:

&#13;
&#13;
$("div").on("click", function()
{
  alert($(this).attr("class"));
  alert($(this).next().attr("class"));
  alert($(this).prev().attr("class"));
  alert($(this).next().hasClass("class1"));
  alert($(this).prev().hasClass("class1"));
});
&#13;
.class1
{
  width:100%;
  height:3rem;
  background:blue;
}
.class2
{
  width:100%;
  height:3rem;
  background:green;
}
.class3
{
  width:100%;
  height:3rem;
  background:yellow;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class1"></div>
<div class="class1"></div>
<div class="class2"></div>
<div class="class1"></div>
<div class="class3"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

//iterate over the divs
$('div[class^="class"]').each(function(){
    //get the previous div with correct class
    var prev = $(this).prev('div[class^="class"]');
    //if there's a previous element and it doesn't match the class
    if(prev.length > 0 && !$(this).hasClass(prev.prop('class'))){
        //add the margin
        $(this).css('margin-top', '10px');
    };
});