jQuery event.which 屬性



jQuery 的event.which屬性用於確定在鍵盤或滑鼠事件期間按下鍵盤或滑鼠的特定鍵或按鈕。

它規範化了 event.keyCode 和 event.charCode,但大多數情況下建議對於鍵盤輸入使用 event.which。

語法

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

event.which

引數

此方法不接受任何引數。

返回值

此屬性返回按下的特定鍵盤鍵或滑鼠按鈕。

示例 1

以下程式演示了 jQuery event.which 屬性的使用:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <style>
        div{
            color: green;
            font-size: 20px;
            font-weight: bolder;
        }
    </style>
</head>
<body>
    <p>Click on the below text.</p>
    <div>Tutorialspoint</div>
    <script>
        $('div').click(function(event){
            alert("The pressed mouse key is: " + event.which);
        })
    </script>
</body>
</html>

輸出

以上程式顯示了一個包含一些文字的 p 元素,當滑鼠指標單擊它時,瀏覽器螢幕上將出現一個彈出警報,顯示您按下了哪個滑鼠按鈕:


當滑鼠單擊顯示的文字時:


示例 2

以下是 jQuery event.which 屬性的另一個示例。我們使用此方法來檢索輸入框內按下的哪個鍵盤或滑鼠鍵:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <style>
    fieldset{
        border: 2px solid green;
        padding: 10px;
        width: 300px;
    }
    div span{
        margin: 20px 10px;
    }
    </style>
</head>
<body>
    <fieldset>
        <legend>MyForm</legend>
        Name: <input type="text" placeholder="Enter your name.."><br>
        <span></span>
    </fieldset>
    <script>
        $(document).ready(function(){
            $('input').keydown(function(event){
                $('span').text("Key pressed: " + event.which);     
            });
        })
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個包含輸入框的表單,當用戶開始在輸入框中輸入內容時,其旁邊將顯示相應的按下鍵:


jquery_ref_events.htm
廣告

© . All rights reserved.