我可以't对jquery上的click事件使用off函数

I can't use off function for click event on jquery

本文关键字:事件 click 函数 off 上的 jquery 我可以      更新时间:2024-05-19

我想在jquery上做可打开的菜单。我使用点击方法,这很有效,但我无法关闭它。我如何关闭它?谢谢:)

$("div#kkayit").on("click", function(){
    $(this).css("background-color", "pink");
});
$("div#kkayit").on("click", function(){
    $("div#kkayit").off("click");
});

您可以在jquery:中使用函数toggle

http://api.jquery.com/toggle/

$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> HERE Will toggle</p>
<button>Toggle between hide() and show()</button>

您已经为同一选择器注册了两次同一事件。所以我建议只使用下面的代码来处理上面提到的选择器的点击事件。

$("div#kkayit").one("click", function(){
    $(this).css("background-color", "pink");
});

http://api.jquery.com/one/

请尝试以下操作:

$("div#kkayit").on("click", function(event){
    $(this).css("background-color", "pink");
    event.preventdefault();
});

请告诉我我是否回答了你的问题。

谢谢。Vinay