使用onInput()事件
onInput()是 HTML5 的標准事件,對於檢測 textarea, input:text, input:password 和 input:search 這幾個元素通過用戶界面發生的內容變化非常有用,在內容修改后立即被觸發,不像 onchange 事件需要失去焦點才觸發。
onInput() 事件在主流瀏覽器的兼容情況如下:
一個小例子:使用正則表達式,非數字就替換為空。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <script type="text/javascript"> function keypress(_this){ _this.value = _this.value.replace(/[^0-9]/g, ''); } </script> <body> <input type="text" onInput ="keypress(this)" /> </body> </html>