jQuery change() 方法



jQuery 事件change() 方法用於繫結(或附加)事件處理程式到 change 事件,或在元素上觸發 change 事件。

當元素的值發生更改時,將發生(或觸發)change 事件。此方法通常與以下元素一起使用:

  • <input>
  • <textarea>
  • <select>

此方法根據是否將函式作為引數傳遞,要麼將函式繫結到 change 事件,要麼在選定的元素上觸發 change 事件。

語法

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

$(selector).change(function)

引數

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

  • 函式(可選) - 每當在選定元素上發生 change 事件時,該函式就會執行。

返回值

此方法不返回值,而是將 change 處理程式附加到選定的元素。

示例 1

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

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Write something in below input field and press enter...</p>
    <input type="text" placeholder="Write...">
    <script>
        $('input').change(function(){
            alert("change event occured")
        });
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個輸入欄位。當用戶在此欄位中輸入文字,然後按回車鍵或單擊欄位外部時,瀏覽器螢幕上將出現一個警報彈出訊息:


當用戶在欄位中輸入內容時:


示例 2

在此示例中,我們透過將事件處理程式附加到選定textarea欄位的 change 事件來演示 jQuery change() 方法。當用戶在文字區域中輸入內容,然後單擊文字區域外部時,輸入的文字將立即顯示在文字區域旁邊:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Write something in below textarea and click outside the field...</p>
    <textarea name="" id="" cols="30" rows="10" placeholder="Write something..."></textarea><br>
    <span></span>
    <script>
        $('textarea').change(function(){
            let x = document.querySelector('textarea');
            document.querySelector('span').innerHTML = x.value;
        });
    </script>
</body>
</html>

輸出

上述程式顯示一個文字區域欄位。每當使用者在其中輸入內容然後單擊欄位外部時,輸入的文字將立即顯示在欄位之後:


一旦使用者在“textarea”欄位中輸入內容:


示例 3

讓我們使用 jQuery 事件change() 方法將事件處理程式繫結到“select”元素的 change 事件。當從 select 欄位中選擇一個選項時,將觸發 change 事件:

<html>
    <head>
        <script type = "text/javascript" src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Select an option.</p>
    <select name="" id="">
        <option value="">Select language...</option>
        <option value="">JavaScript</option>
        <option value="">TypeScript</option>
        <option value="">Java</option>
        <option value="">Python</option>
    </select>
    <script>
        $('select').change(function(){
            alert("Option has been changed....");
        });
    </script>
</body>
</html>

輸出

執行上述程式後,它將顯示一個 select 欄位。當用戶選擇一個選項時,將發生 change 事件(在選擇選項之前):


一旦使用者選擇一個選項:


jquery_ref_events.htm
廣告
© . All rights reserved.