限制文本输入时带一些特殊符号
1. 首先是实时获取Html中 输入的值
- html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>title>
- head>
- <body>
- <input id="test" oninput="app()" />
-
- <script>
- function app() {
- const test =document.getElementById('test');
- console.log(test.value)
- }
- script>
- body>
- html>
oninput 事件是在输入框中输入时就会触发,该事件在或
onchange 事件是在输入框输入完内容后,输入框失焦后触发。且onchange事件也可以作用于
2. 根据输入的值进行输入判断
对于输入的文本进行判断的方法有很多种
(1)includes
- const test = document.getElementById('test');
- const tagTest = '' // 想检测的字符段
-
- if(test.value.toString().includes(tagTest )){
- // 包含的操作
- }else{
- // 不包含的操作
- }
在使用 includes 方法时候,需要注意的是必须转换成 string 或者 数组,否则将会报错
converted the number to a string using the
toString()method before we called theincludesmethod.we used the
Array.frommethod to convert aSetto an array before calling theincludesmethod.
(2)indexOf
- const test = document.getElementById('test');
- const tagTest = '' // 想检测的字符段
-
- if(test.value.indexOf(tagTest) == -1){
- // 包含的操作
- }else{
- // 不包含的操作
- }
使用 indexOf 的方法最主要体现在其返回的数组的索引,而不是布尔值。
(3) 正则表达式判断
- const test = document.getElementById('test');
-
- if(/[~!@#$%^&*_+-=\[\]{}]/.test(test.value)){
- // 包含的操作
- }else{
- // 不包含的操作
- }
正则表达式是最简洁方面的,因为上面的两种方式都需要一个一个写出来,当出现你需要过滤一系列的值得时候就会导致代码方法十分长,同时效率并不高。