jQuery 事件 keypress() 方法



jQuery 事件keypress()方法用於將事件處理程式附加到keypress事件或觸發所選元素上的該事件。當按下鍵盤鍵時發生。

keypresskeydown事件非常相似;但是,關鍵區別在於keypress事件並非對所有鍵(例如ALT、CTRL、SHIFT和ESC等非列印鍵)都觸發,而keydown事件則會觸發。

語法

以下是jQuery事件keypress()方法的語法:

$(selector).keypress(function)

引數

此方法接受一個可選引數'function',如下所述:

  • function - 當keypress事件發生時執行的可選函式。

返回值

此方法不返回任何值,而是將函式附加到keypress事件。

示例 1

以下程式演示了jQuery事件keypress()方法的用法:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Press the enter to see the pop-up message on your browser screen.</p>
    <script>
        $(document).keypress(function(){
            alert("User presssed the key");
        });
    </script>
</body>
</html>

輸出

上述程式在使用者按下任何鍵(除了非列印鍵)時顯示一條訊息,您的瀏覽器螢幕上將出現一個警報彈出訊息:


當用戶按下按鍵時:


示例 2

以下是jQuery事件keypress()方法的另一個示例。在這裡,我們使用此方法與輸入欄位一起檢索輸入值和按鍵次數,無論何時使用者開始向輸入欄位輸入值:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Enter any name in the below input field</p>
    <input type="text" placeholder="Your name">
    <p id="result"></p>
    Count: <span>0</span>
    <script>
        let i = 0;
        $('input').keypress(function(){
            let data = $(this).val();
            document.getElementById("result").innerHTML = data;
            $('span').text(i = i + 1);
        });
    </script>
</body>
</html>

輸出

執行程式後,將顯示一個輸入欄位。無論何時使用者開始鍵入內容,輸入的資料都將與同時按下鍵盤的次數一起顯示在瀏覽器螢幕上:


當用戶開始在欄位中輸入輸入值時:


示例 3

在下面的示例中,我們聲明瞭一個包含8種不同顏色的陣列。每當觸發keypress事件時,都會將此陣列中的顏色分配給div元素。當用戶按下任何鍵時,div元素的顏色將相應更改:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<style>
    div p{
        font-size: 30px;
		font-style: bolder;
    }
</style>
<body>
    <p>Press any key and release to toggle the below div background-color</p>
    <div>
        <p>TutorialsPoint</p>
    </div>
<script>
    let colors = ['red', 'blue', 'green', 'grey', 'black', 'white', 'teal', 'yellow'];
    let i = 0;
    $(document).keypress(function(event) {
        $('div').css('color', colors[i]);
        i++;
        i = i % colors.length;
});
</script>
</body>
</html>

輸出

執行上述程式後,將顯示文字。每當使用者按下任何鍵時,顯示文字的顏色都會每次更改:


當用戶按下任何鍵時,隨機顏色將分配給顯示的文字:


再次!使用者按下任何鍵,顏色這次更改為“紅色”


jquery_ref_events.htm
廣告

© . All rights reserved.