jQuery使用.off取消绑定单击处理程序,然后使用.on重新绑定

时间:2017-08-28 17:42:54

标签: javascript jquery

我试图阻止按钮被意外点击两次,方法是将点击处理程序与.off一起取消绑定...



$(".button").click(function () {
    console.log("Button has been clicked and disabled");
		$( ".button" ).off();
});

$(".button2").click(function () {
    console.log("Button has been re-enabled");
		$( ".button" ).on();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">
    Click Me
</div>

<button class="button2">
    Re-enable click
</button>
&#13;
&#13;
&#13;

我正在努力用.on重新绑定它,有人能指出我的方向或指出我做错了吗?

2 个答案:

答案 0 :(得分:2)

在按钮2的点击功能中,重新启用第一个按钮的点击处理:$(".button").click(buttonOneClick); 这是一个例子:

var buttonOneClick = function () {
    console.log("Button has been clicked and disabled");
		$( ".button" ).off();
};
$(".button").click(buttonOneClick);

$(".button2").click(function () {
    console.log("Button has been re-enabled");
    $(".button").click(buttonOneClick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">
    Click Me
</div>

<button class="button2">
    Re-enable click
</button>

答案 1 :(得分:2)

使用.one()

使用.one()不需要使用.off(),因为该事件只允许使用一次。要重新启用该按钮,只需重新调用执行.one()内容的启用功能:

function buttonExec() {
  console.log("Button has been clicked and disabled");
}

function buttonEnable() {
  console.log("Button has been enabled");
  $(".button").one("click", buttonExec); // .one()
}

buttonEnable();                          // enable initially
$(".enable").on("click", buttonEnable);  // and on ".enable" click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="button">Click Me</button>
<button class="enable">Re-enable click</button>

使用.on().off()

function buttonExec() { 
  console.log("Button has been clicked and disabled");
  $(this).off("click");                  // .off() since we used .on()
}

function buttonEnable() {
  console.log("Button has been enabled");
  $(".button").on("click", buttonExec);  // .on()
}

buttonEnable();                          // enable initially
$(".enable").on("click", buttonEnable);  // and on ".enable" click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="button">Click Me</button>
<button class="enable">Re-enable click</button>