我目前class ="screenPower"
位于class="screenItem"
内。
on screenItem
我有点击事件:
$(".screenItem").click(function() {
var clickedbutton = this;
}
我的问题是:点击后如何将screenPower screenOff
更改为screenPower screenOn
?点击screenOff
后,应关闭当前有效screenOn
。 - 换句话说 - 一次只有一个屏幕可以screenOn
。
我基本上想要做的是:
if(clicked && == "screenPower screenOff) {
//change target class to screenPower screenOn
//change current active class to screenPower screenOff
}
HTML
<div class="screenItem">
<div class="screenImage1"> <span></span>
<img src="images/img.gif" class="img-rounded img-responsive" alt="KSRasmussen" />
</div>
<div class="screenPower screenOn"></div>
</div>
<div class="screenItem">
<div class="screenImage1"> <span></span>
<img src="images/img.gif" class="img-rounded img-responsive" alt="KSRasmussen" />
</div>
<div class="screenPower screenOff"></div>
</div>
答案 0 :(得分:4)
点击screenItem
后,检查是否有.screenOff
后代。如果是,那么您可以找到所有screenPower
元素,并使用toggleClass
函数添加和删除screenOff
和screenOn
类:
$(".screenItem").click(function() {
if($(this).find('.screenOff').length > 0) {
$('.screenPower').toggleClass('screenOff screenOn');
}
});
这假设screenPower
以screenOff
或screenOn
开头,您的示例似乎就是这种情况。
<强> Working Demo 强>
答案 1 :(得分:0)
$(".screenItem").click(function() {
var wasOn = $(this).hasClass('screenOff');
$(this).removeClass('screenOff screenOn');
$(this).addClass(wasOn ? 'screenOff' : 'screenOn');
var clickedbutton = this;
}
答案 2 :(得分:0)
将它放在点击处理程序中:
// remove the previous screen On
$('.screenPower .screenOn').removeClass('screenOn').addClass('screenOff');
// make the clicked one active
$(this).find('.screenPower').removeClass('screenOff').addClass('screenOn');