jQuery event.namespace 屬性



jQuery 的 event.namespace 屬性用於指定事件觸發時的名稱空間。當事件觸發時,它會返回指定的或自定義的名稱空間。

在 jQuery 中,名稱空間是一個封裝函式、變數和其他物件的物件。它提供了一種組織和分組相關程式碼以及防止命名衝突的方法。

語法

以下是 jQuery event.namespace 屬性的語法:

event.namespace

引數

  • 此方法不接受任何引數。

返回值

此屬性在事件觸發時返回自定義的名稱空間。

示例 1

繫結帶有名稱空間的事件。

以下是 jQuery event.namespace 屬性的基本示例:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        p{
            font-size: 20px;
            color: green;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <p>Click on me</p>
    <script>
    $("p").on("click.TutorialsPoint", function(event) {
        alert("Event namespace is: " + event.namespace);
    });
    </script>
</body>
</html>

輸出

以上程式顯示了一個按鈕。當單擊按鈕時,它會顯示“undefined”作為名稱空間,在事件未觸發之前,它將返回 undefined。


當單擊按鈕時:


示例 2

觸發帶有名稱空間的事件。

以下是 jQuery event.namespace 屬性的另一個示例。我們使用此方法來指定和檢索事件觸發時的名稱空間:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        div{
            width: 200px;
            padding: 10px;
            background-color: green;
            color: white;
        }
    </style>
</head>
<body>
    <p>Mouse enter on the below box</p>
    <div>TutorialsPoint</div><br>
    <button>Remove</button><br>
    <span></span>
    <script>
    $("div").on("mouseenter.TutorialsPoint", function(event) {
        $('span').text("Event namespace is: " + event.namespace);
        $('span').css("color", "green");
    });
    $("div").on("mouseenter", function(){
        $(this).trigger("mouseenter.TutorialsPoint");
    })
    $('button').click(function(){
        $('div').off("mouseenter.TutorialsPoint");
        $('span').text("Removed...!");
        $('span').css("color", "red");
    });
    </script>
</body>
</html>

輸出

執行上述程式後,它會顯示一個 <div> 元素和一個按鈕,當滑鼠指標進入“div”元素時,名稱空間將被顯示,當單擊按鈕時,名稱空間將被移除。


jquery_ref_events.htm
廣告