以往 HTML 的 input 輸入框,無法即時反映使用者的輸入內容。
onkeyup、onkeydown 事件,無法即時、精確地取得使用者的輸入資料;而 onchange、onblur 事件,要等到失去焦點時,或按下 Enter 時,才會被觸發。

現在 HTML5 新增的 input 事件,可達成「立即、精準地觸發」,類似 AJAX 功能。唯一的缺點,是不支援 IE 瀏覽器,但支援其他各瀏覽器。

如下 html 程式碼,可測試出,input 事件可達成「立即、精準地觸發」;舊有的 change 事件,則需要失去焦點時,或按下 Enter 時,才會被觸發。

 1 <!DOCTYPE html>
 2 <html >
 3 <head>    
 4     <script>
 5         function myFunc1(input) {
 6             document.getElementById("output1").value = input;
 7         }
 8         
 9         function myFunc2(input) {
10             document.getElementById("output2").value = input;
11         }
12     </script>
13 </head>
14 <body>
15     <input id="input1" type="text" oninput="myFunc1(this.value)" />
16     <br />
17     <input id="input2" type="text" onchange="myFunc2(this.value)" />
18     <p></p>
19     <output id="output1"></output>
20     <br />
21     <output id="output2"></output>
22 </body>
23 </html>
oninput、onchange 比較

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2021-07-30
  • 2022-03-02
  • 2021-04-17
  • 2022-12-23
  • 2022-01-30
猜你喜欢
  • 2021-12-09
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案