我有一个功能:
function maskInput(input, location, delimiter, length) {
//Get the delimiter positons
var locs = location.split(',');
//Iterate until all the delimiters are placed in the textbox
for (var delimCount = 0; delimCount <= locs.length; delimCount++) {
for (var inputCharCount = 0; inputCharCount <= input.length; inputCharCount++) {
//Check for the actual position of the delimiter
if (inputCharCount == locs[delimCount]) {
//Confirm that the delimiter is not already present in that position
if (input.substring(inputCharCount, inputCharCount + 1) != delimiter) {
input = input.substring(0, inputCharCount) + delimiter + input.substring(inputCharCount, input.length);
}
}
}
}
input = input.length > length ? input.substring(0, length) : input;
return input;
}
我在:
中使用它$(document).on('keypress paste drop blur', '#my_phone_number', function() {
//remove any nondigit characters
var myVal = $(this).val().toString().replace(/\D/g,'');
$(this).val(myVal);
var inVal = maskInput(myVal, '3,7', '-', 12);
$(this).val(inVal);
});
这很好用,但是当我尝试从字符串中间删除一个数字然后再添加它时,它会将它附加到字符串的末尾,不会粘到当前位置。
示例:
Entered String: '1234567890'
After Mask Function Is Called: '123-456-7890'
Number 5 removed and entered Number 8 instead of 5: '123-467-8908'
请注意,它在字符串末尾附加了数字 8 。
感谢任何帮助,谢谢
答案 0 :(得分:1)
您应该使用keyup
而不是keypress
,因为在keypress
上输入的值尚未更改,并且在将新值发布到输入之前应用过滤器。这就是为什么要追加新角色的原因。
$(document).on('keyup paste drop blur', '#my_phone_number', function() {
...
});
此处的工作代码示例http://jsbin.com/upinux/1/edit