輸入框input,的type設置為number,本想只輸入數字,但是字符“e”卻能通過,
首先科普一下,
<body> <input onkeypress="getCode(event)" /> </body>
<script>
function getCode(e){
console.log(e.keyCode);
}
</script>
每次在輸入框輸入,我們可以拿到一個event.keyCode,他是一個unicode值。
String.fromCharCode:可以將一個unicode碼轉換了他對應的值
輸入:b 98 ->b
現在我們已經能獲取到輸入的值了,接下來就是,用一個正則表達式,進行過濾
/[\d]/:匹配一個數字字符
所以.......
以下禁止字符“e”的輸入(應該是禁止一切字符,)
<input type="number" onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode))"/>
當不滿足這個正則的時候,就返回一個false,輸入框不顯示。