代码之家  ›  专栏  ›  技术社区  ›  grt812

在事件jquery中使用off()

  •  1
  • grt812  · 技术社区  · 7 年前
    $(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 回复  |  直到 7 年前
        1
  •  0
  •   FatalMerlin    7 年前

    要引用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 .