jQuery event.type 屬性



jQuery 的event.type屬性用於檢索觸發的事件型別。它用於事件處理函式中,並返回在特定元素或文件上發生的事件型別。

語法

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

event.type

引數

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

返回值

此屬性返回觸發的事件型別。

示例 1

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

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below button to see the event type.</p>
    <button>Click me</button>
    <script>
        $('button').click(function(event){
            alert("The trigegerd event is: '" + event.type + "' type");
        });
    </script>
</body>
</html>

輸出

程式顯示一個按鈕,單擊時,瀏覽器螢幕上會出現一個彈出警報,顯示按鈕元素觸發的事件型別,如下所示:


單擊按鈕時:


示例 2

以下是 jQuery event.type 屬性的另一個示例。我們使用此屬性來檢索在特定 div 元素上觸發的事件型別:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <style>
        div{
            width: 300px;
            padding: 10px;
            background-color: green;
            color: white;
        }
    </style>
</head>
<body>
    <div>Hover on me</div>
    <span></span>
    <script>
       $('div').mouseover(function(event){
        $('span').text("The triggered event was '" + event.type + "'");
       });
    </script>
</body>
</html>

輸出

程式執行後,將顯示一個具有綠色背景的框。當滑鼠指標懸停在此框上時,事件型別將顯示在其旁邊:


示例 3

在下面的示例中,我們在按鈕元素上分配多個事件,例如“click”、“mouseover”和“mouseout”,並使用event.type屬性檢索觸發的事件型別:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <style>
        div{
            width: 300px;
            padding: 10px;
            background-color: green;
            color: white;
        }
        button{
            padding: 10px;
            margin: 10px 0px;
            width: 100px;
        }
    </style>
</head>
<body>
    <p>Click, over, out the mouse pointer on the below button</p>
    <button>Button</button>
    <p>The event type will be displayed here: </p>
    <div></div>
    <script>
       $("button").on("click dblclick mouseover mouseout", function(event) {
          $("div").html("Event: " + event.type);
    });
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個按鈕,當用戶單擊、懸停或移出按鈕時,觸發的事件將顯示在其旁邊,如下所示:


jquery_ref_events.htm
廣告
© . All rights reserved.