jquery和vue分别对input输入框手机号码格式化(344)

jQuery

function fomatterTel(val, old) {//val: 当前input的值,old: input上次的值
var str = "";
var telLen = val.length;
if (old.length <= telLen) {
if (telLen === 4 || telLen === 9) {
var pre = val.substring(0, telLen-1);
var last = val.substr(telLen-1, 1);
str = pre + ' ' + last;
} else {
str = val;
}
} else {
if (telLen === 9 || telLen === 4) {
str = val.trim();
} else {
str = val;
}
}
return str;
}

1.input的输入事件最好用oninput事件监听,用keyup的话会有闪烁,不过看不太出来,也能用。jquery的input事件要用bind绑定,不能直接写$("#input1").input这样写会报错, 要写成$("#input1").bind('input', function(){});

2.old的获取也很简单

var oldTelephone = $("#telephone").val();//输入前先获取一次
$("#telphone").bind('input',function () {
$("#telephone").val(fomatterTel($("#telephone").val(), oldTelephone));
oldTelephone = $("#telephone").val();//输入后保存old为下一次输入做准备
});

vue获取

data中存入telephone: ''。input的v-model为telephone 。在watch中监听telephone

<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;
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/miss1332/p/9861083.html