在div框被着色后如何使点击功能停止工作?

时间:2015-12-18 11:06:07

标签: javascript

我在点击功能上有一个框,当你点击它时,它会变成红色或蓝色。 有没有办法让盒子上色后点击功能停止工作。 如果框是彩色的,则单击功能应停止工作。 THX!

代码;

if (box1.style.backgroundColor == "red" || box1.style.backgroundColor == "blue") {
            $("#box1").click(function (){
                // return nothing 
            });
        }

换色代码:

$("#box1").click(function () {
        clickCounter++;
        if (clickCounter % 2 == 0) {
            box1.style.backgroundColor = "red";
        } else {
            box1.style.backgroundColor = "blue";
        }

5 个答案:

答案 0 :(得分:2)

您可以使用$.off()删除任何活动。以下是描述相同的代码。

  

$.off()

$(".oneClick").on("click", function(){
  var color = (Math.random()*10).toFixed(0)%2 == 0?"red":"blue"
  $(this).css({"background" : color});
  $(this).off("click");
})
.oneClick{
  width:60px;
  height:60px;
  border:2px solid gray;
  background:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="oneClick"></div>

答案 1 :(得分:1)

使用jQuery unbind function 的最简单方法:

$("#box1").click(function () {
    clickCounter++;
    if (clickCounter % 2 == 0) {
        box1.style.backgroundColor = "red";
        $( "#box1").unbind( "click" );
    } else {
        box1.style.backgroundColor = "blue";
        $( "#box1").unbind( "click" );
    }

答案 2 :(得分:1)

当您使用$.click()方法定义eventListener时,可以按以下方式删除它:

$('.clickbox').on('click', function() {
  var $currentBox = $(this); // get the box you just clicked (this is the method you need)

  $currentBox.css({
    backgroundColor: 'red'
  })  

  $currentBox.off('click'); // remove the click event listener
})

例: http://codepen.io/anon/pen/MKyOwO

答案 3 :(得分:1)

我更愿意添加和删除一个监听器,我认为它更干净like this

答案 4 :(得分:0)

将if语句放在click事件

$("#box1").click(function (){
   if (box1.style.backgroundColor == "red" || box1.style.backgroundColor == "blue") {
      return false;
   }

    // your code 
    clickCounter++;
    if (clickCounter % 2 == 0) {
        box1.style.backgroundColor = "red";
    } else {
        box1.style.backgroundColor = "blue";
    }
});