使用另一个按钮反转由.off()方法导致的事件处理程序的删除

时间:2018-04-03 02:31:29

标签: jquery

我一直在谷歌搜索想要解决这个问题的时间。

基本上我的情况是我必须找到一种方法反向删除由.off()方法导致的事件处理程序。

换句话说,我希望能够使用另一个按钮重新启动p标记的事件处理程序。我怎样才能做到这一点?这是我的代码示例:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").on("click", function(){
        $(this).css("background-color", "pink");
    });
    $("#turn-off").click(function(){
        $("p").off("click");
        $('p').css("background-color", "white");
    });
    
    $("#reverse").click(function(){
       //???
    });
});
</script>
</head>
<body>

<p>Click this paragraph to change its background color.</p>
<p>Click the button below and then click on this paragraph (the click event is removed).</p>

<button id='turn-off'>Remove the click event handler</button>

<button id='reverse'>Reverse the removal of the click event handler</button>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

重新打开它只是再次调用.on。而且,既然你再次回复.on,你就需要提供所有论据 - 正如你第一次做的那样。

为简化起见,您可以将调用.on的代码移动到函数中,并在#reverse点击逻辑中使用它。

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    function turnOn() {
      $("p").on("click", function(){
        $(this).css("background-color", "pink");
      });
    }
    turnOn(); // initial setup
    $("#turn-off").click(function(){
        $("p").off("click");
        $('p').css("background-color", "white");
    });
    
    $("#reverse").click(function(){  // or, simply: $("#reverse").click(turnOn);
       turnOn();
    });
});
</script>
</head>
<body>

<p>Click this paragraph to change its background color.</p>
<p>Click the button below and then click on this paragraph (the click event is removed).</p>

<button id='turn-off'>Remove the click event handler</button>

<button id='reverse'>Reverse the removal of the click event handler</button>

</body>
</html>
&#13;
&#13;
&#13;


另外,我建议您使用namespaced events,以后会为您节省一些麻烦(请注意click.foo而不是click的使用情况,foo命名空间:

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    function turnOn() {
      $("p").on("click.foo", function(){
        $(this).css("background-color", "pink");
      });
    }
    turnOn(); // initial setup
    $("#turn-off").click(function(){
        $("p").off("click.foo");
        $('p').css("background-color", "white");
    });
    
    $("#reverse").click(turnOn);
});
</script>
</head>
<body>

<p>Click this paragraph to change its background color.</p>
<p>Click the button below and then click on this paragraph (the click event is removed).</p>

<button id='turn-off'>Remove the click event handler</button>

<button id='reverse'>Reverse the removal of the click event handler</button>

</body>
</html>
&#13;
&#13;
&#13;