我想在点击另一个类时向div
添加一个类。
当我点击一个div
所有获得的课程时,我的代码就是白色。
我的jQuery是:
$(".front").click(function (event) {
// remove classes from all
$('.front .back').not($(this)).removeClass('back-Active');
// add class to the one we clicked
$('.front .back').addClass("back-Active");
event.stopPropagation();
});
我怎么解决这个问题?
答案 0 :(得分:2)
使用this
对当前元素的引用
$(".front").click(function (event) {
// remove classes from all
$('.front .back').removeClass('back-Active'); //line changed to remove back-Active from all
// add class to the one we clicked
$(this).find('.back').addClass("back-Active"); //this line changed to add back-Active to only current element
event.stopPropagation();
});
如果您还要将课程添加到.front
元素,请尝试
$(".front").click(function (event) {
$('.front, .front .back').removeClass('back-Active');
$(this).addClass("back-Active");
$(this).find('.back').addClass("back-Active");
event.stopPropagation();
});
答案 1 :(得分:1)
在事件处理程序中使用$(this)
来引用单击的元素。
$('.back', this) // Select the element inside clicked element having `back` class
.addBack(this) // Add clicked element to the set
.addClass("back-Active"); // Add class on the elements
$(document).on('click', function() {
$('.back').removeClass("back-Active");
});
$(".front").click(function(event) {
// remove classes from all
$('.back-Active').removeClass('back-Active');
// add class to the one we clicked
$('.back', this).addBack(this).addClass("back-Active");
event.stopPropagation();
});
.back-Active {
transform: scale(1.0) !important;
opacity: 1 !important;
transition: 400ms ease;
}
.front {
background-color: red;
width: 100px;
height: 100px;
margin: 20px;
}
.back {
transform: scale(0.0);
opacity: 0;
background-color: green;
width: 100px;
height: 100px;
margin-top: -18px;
transition: 400ms ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="front">
AAA
<div class="back">AAA-BACK</div>
</div>
<div class="front">
BBB
<div class="back">BBB-BACK</div>
</div>
<div class="front">
CCC
<div class="back">CCC-BACK</div>
</div>
<div class="front">
DDD
<div class="back">DDD-BACK</div>
</div>