根据类名值更改类名

时间:2013-08-02 14:35:34

标签: jquery css class

我目前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>

3 个答案:

答案 0 :(得分:4)

点击screenItem后,检查是否有.screenOff后代。如果是,那么您可以找到所有screenPower元素,并使用toggleClass函数添加和删除screenOffscreenOn类:

$(".screenItem").click(function() {
    if($(this).find('.screenOff').length > 0) {
        $('.screenPower').toggleClass('screenOff screenOn');
    }
});

这假设screenPowerscreenOffscreenOn开头,您的示例似乎就是这种情况。

<强> 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');