我有一个功能:
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 。
任何帮助表示赞赏,谢谢