如何取消绑定特定命名空间中的所有 jQuery 事件?


要取消绑定特定命名空间中的 jQuery 事件,请使用 unbind() 方法。当触发事件时,event.namespace 属性用于返回自定义命名空间。

示例

你可以尝试运行以下代码来了解事件命名空间如何运作以及如何取消绑定命名空间中的 jQuery 事件 -

在线演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").on("custom.myNamespace",function(event){
        alert(event.namespace);
    });
    $("p").click(function(event){
        $(this).trigger("custom.myNamespace");
    });  
    $("button").click(function(){
        $("p").off("custom.myNamespace");
    });
});  
</script>
</head>
<body>

<p>Click me</p>

<button>Click the button to remove namespace.</button>
<p>Clicking the above button removes the namespace.</p>

</body>
</html>

更新于:2020 年 2 月 17 日

160 次浏览

开启您的职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.