如何将一个类添加到上一个div [英] How to add a class to previous div

查看:65
本文介绍了如何将一个类添加到上一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将类添加到当前"类之前的第一个div中.

<div></div>
<div></div>
<div class="current">Current</div>
<div ></div>
<div></div>

我只是找到了下一个div的方法,但仍在寻找解决方案以使该类更早.

$(document).ready(function(){
    $(".current + div").addClass("prv");
});

https://fiddle.jshell.net/0d7csqgb/2/

有人知道我该怎么做吗?

//编辑

如果有人需要,这里是可行的解决方案: https://fiddle.jshell.net/df9ef0hf/6/

解决方案

您可以使用prev函数.

 $(document).ready(function() {
  $(".current").prev().addClass("prv");
}); 

 .prv{
background-color: red;
} 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>one</div>
<div>two</div>
<div class="current">Current</div>
<div>tree</div>
<div>four</div> 

I need to add class to the first div before the "current" class.

<div></div>
<div></div>
<div class="current">Current</div>
<div ></div>
<div></div>

I just found out how to do it for the next div but still looking for solution to get the class before it.

$(document).ready(function(){
    $(".current + div").addClass("prv");
});

https://fiddle.jshell.net/0d7csqgb/2/

Do anyone know how I can do it?

//EDIT

Here's working solution if somebody need: https://fiddle.jshell.net/df9ef0hf/6/

解决方案

You can use prev function..

$(document).ready(function() {
  $(".current").prev().addClass("prv");
});

.prv{
background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>one</div>
<div>two</div>
<div class="current">Current</div>
<div>tree</div>
<div>four</div>

这篇关于如何将一个类添加到上一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆