jquery add class onclick包括div

时间:2018-03-05 19:28:22

标签: jquery onclick

请问我该如何创作? 点击包括div灰色更改背景prev div红色只点击框,其他男孩白色



$('.box .center').click(function() {
   $('.box').removeClass('red');
   $('.box').addClass('red');
});

.box {
    width: 250px;
    height: 100px;
    border: 1px #000 solid;
    margin: 2px 0;
}

.red {
    background: red;
}
.center {margin: 40px 100px; width: 50px; height: 25px; background: gray;  display: block; cursor:pointer;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'>
  <div class="center"></div>
</div>
<div class='box'>
  <div class="center"></div>
</div>
<div class='box'>
  <div class="center"></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

这就是你要找的东西吗?

$('.box .center').click(function() {
   $('.box').removeClass('red');
   $(this).parent('.box').addClass('red');
});
.box {
    width: 250px;
    height: 100px;
    border: 1px #000 solid;
    margin: 2px 0;
}

.red {
    background: red;
}
.center {margin: 40px 100px; width: 50px; height: 25px; background: gray;  display: block; cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'>
  <div class="center"></div>
</div>
<div class='box'>
  <div class="center"></div>
</div>
<div class='box'>
  <div class="center"></div>
</div>