jQuery blur() 事件方法



jQuery 事件blur() 方法用於在選定的元素上觸發 blur 事件,或者繫結(或附加)一個在 blur 事件發生時執行的函式。此方法通常與<input><textarea> 欄位一起使用,以便在使用者點選它們外部時失去焦點。

語法

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

$(selector).blur(function)

引數

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

  • function (可選) - 當 blur 事件發生在選定的元素上時要執行的函式。

返回值

此方法不返回值,但會在選定的元素上觸發 blur 事件。

示例 1

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

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <input type="text" placeholder="Your name">
    <p>Enter something in input field and click outside the input field to lose the focus.</p>
    <script>
        $('input').blur(function(){
            alert("Input contents: " + $(this).val());
        });
    </script>
</body>
</html>

輸出

程式執行後,將顯示一個輸入欄位。當用戶在此欄位中輸入一些內容,然後點選其外部時,該欄位將失去焦點(觸發 blur 事件):


點選“確定”按鈕後,您將看到輸入欄位失去了焦點:


示例 2

以下是 jQuery 事件blur() 方法的另一個示例。在這裡,我們使用此方法繫結一個將在 blur 事件發生(觸發)在選定的元素上時執行(執行)的函式:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Enter something in textarea field and click outside the field to lose the focus.</p>
    <p>Write your feedback</p>
    <textarea name="" id="" cols="30" rows="10" placeholder="feedback...."></textarea>
    <span></span>
    <script>
        $('textarea').blur(function add(){
            document.querySelector('span').innerHTML = $(this).val();
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一個文字區域欄位。當用戶輸入文字,然後點選欄位外部時,將觸發 blur 事件,並且該欄位將失去焦點:


jquery_ref_events.htm
廣告

© . All rights reserved.