防止jquery toggleClass执行

时间:2018-03-22 20:20:55

标签: javascript jquery button

单击时,大按钮会在每次单击时切换红色背景。
是否有办法阻止该功能执行,例如单击按钮或执行条件时?

var counter = 0;

$(".btn").on('click', function (e) {
counter++;   
e.preventdefault;
 $(".btn").toggleClass('bgRed');
}).on('animationend', function(e) {
    $(".btn").toggleClass('bgRed');
});


$(".btn2").on('click', function (e) {
// stop toggle on .btn
});
.bgRed{background:red}
.btn{width:340px;height:100px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn">click to Toggle </button>

<button class="btn2">Stop Toggle </button>
<button class="btn3">Continue Toggle </button>

3 个答案:

答案 0 :(得分:4)

var counter = 0;

$(".btn").on('click', function(e) {
  counter++;
  e.preventDefault();

  if (!$(this).hasClass('toggleOff')) {
    $(".btn").toggleClass('bgRed');
  }
}).on('animationend', function(e) {
  if (!$(this).hasClass('toggleOff')) {
    $(".btn").toggleClass('bgRed');
  }
});


$(".btn2").on('click', function(e) {
  $('.btn').toggleClass('toggleOff');
});
.bgRed {
  background: red
}

.btn {
  width: 340px;
  height: 100px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn">click to Toggle </button>

<button class="btn2">Stop Toggle </button>

答案 1 :(得分:1)

在切换颜色之前,将切换添加到已检查的外部范围。让另一个按钮打开/关闭切换开关,然后重新设置。

&#13;
&#13;
var counter = 0;

//toggle this to enable/disable the background color switching.
let enabledBackgroundChange = true;

$(".btn").on('click', function (e) {
    counter++;   
    e.preventdefault;
    if(enabledBackgroundChange){
        $(".btn").toggleClass('bgRed');
    }
});


$(".btn2").on('click', function (e) {
    // stop toggle on .btn
    enabledBackgroundChange = !enabledBackgroundChange;
});
&#13;
.bgRed{background:red}
.btn{width:340px;height:100px}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn">click to Toggle </button>

<button class="btn2">Stop Toggle </button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以从按钮中取消绑定事件,如下所示:

var counter = 0;

function setBtnToggle() {
    $(".btn").on('click', function (e) {
       counter++;   
       e.preventdefault;
       $(".btn").toggleClass('bgRed');
    }).on('animationend', function(e) {
        $(".btn").toggleClass('bgRed');
    });
}

$(".btn2").on('click', function (e) {
    $(".btn").off('click').off('animationend');  
});

$(".btn3").on('click', function (e) {
    setBtnToggle();
});

//set this up for page load.
setBtnToggle();