在事件jquery中使用off()

时间:2018-07-26 15:48:43

标签: javascript jquery

$(function(){
    $("#selector").on("someevent", function(){
        let variable = some_value;
        $("#anotherselector").click(function(){
            //code involving variable here
            if(condition){
                $(this).off(reference to click event here); 
            }   
        });
    });
});

是否可以从其处理程序内部关闭事件?我正在尝试执行类似上面的代码的操作,并且只需要关闭特定的点击事件(每个点击事件都不同)就可以关闭它。

1 个答案:

答案 0 :(得分:0)

要引用click事件,只需将其传递给'click'和禁用该事件的选择器即可:

$(function(){
    $("#selector").on("someevent", function(){
        $("#anotherselector").click(function(){
            if(condition){
                $('#anotherselector').off('click'); 
            }   
        });
    });
});

let numHandler = 0;
$('#register').click(function () {
  let counter = 0;
  let num = ++numHandler;
  $('#clickme').click(function handler () {
    counter++;
    console.log(`Handler ${num} clicked!`);
    if (counter == 3) $('#clickme').off('click', handler);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickme">Click me!</button>
<button id="register">Register new handler</button>

您可以了解有关关闭功能in the jQuery documentation的更多信息。