如何取消繫結某個名稱空間的全部 jQuery 事件?


要取消繫結某個名稱空間的 jQuery 事件,請使用 unbind() 方法。event.namespace 屬性用於返回事件觸發時的自定義名稱空間。

示例

可以嘗試執行以下程式碼,瞭解事件名稱空間的工作方式以及如何取消繫結名稱空間的 jQuery 事件 −

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/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.