One, jquery
fomatterTel function (val, old) { // fall: input当前的值, old: input上次的值 var str = "" ; var count = val.length; if (old.length <= count) { if (count === 4 || counting === 9 ) { var pre val.substring = ( 0 , Count 1 ); var load = val.substr (practically count 1 , 1 ); str = pre + ' ' + charge; } Else { str = val; } } Else { if (count === 9 || count === 4 ) { str = val.trim (); } Else { str = val; } } Return str; }
Every incoming new and the old val val, can be friends.
Note:
Enter event 1.input best use oninput event listener, use keyup then there will be flashing, but look not out, can also be used. The input to use jquery event bind bind, can not write $ ( "# input1") will write directly input error, to write $ ( "# input1") bind ( 'input', function () {})..;
2.old acquisition is also very simple
var oldTelephone = $ ( " #telephone " ) .val (); // first time before obtaining input $ ( " #telphone " ) .bind ( ' INPUT ' , function () { $ ( " #telephone " ) .val ( fomatterTel ($ ( " #telephone " ) .val (), oldTelephone)); oldTelephone = $ ( " #telephone " ) .val (); // enter save old prepare for the next input });
Two, vue in
The same, only better vue get old, data stored in the telephone: ''. input of the v-model for the telephone. In the telephone listening watch
<input v-model='telephone'> data () { return { telephone: '' } }, watch: { telephone (newValue, oldValue) { if (newValue > oldValue) { if (newValue.length === 4 || newValue.length === 9) { var pre = newValue.substring(0, newValue.length - 1); var last = newValue.substr(newValue.length - 1, 1); this.telephone = pre + ' ' + last; } else { this.telephone = newValue; } } else { if (newValue.length === 9 || newValue.length === 4) { this.telephone = this.telephone.trim(); } else { this.telephone = newValue; } } } }
Source: https://blog.csdn.net/qq_38627581/article/details/80599485