当在中间JavaScript /jQuery中插入字符时,自定义掩码函数不起作用
我有一个功能:当在中间JavaScript /jQuery中插入字符时,自定义掩码函数不起作用,javascript,jquery,regex,Javascript,Jquery,Regex,我有一个功能: 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
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;
}
这非常有效,但当我尝试从字符串中间删除一个数字,然后再次添加它时,它会将其附加到字符串的末尾,而不会固定到当前位置
例如:
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
非常感谢您的帮助,谢谢您应该使用
keyup
而不是keypress
,因为在keypress
上,输入的值尚未更改,并且在将新值发布到输入之前应用过滤器。这就是添加新字符的原因
$(document).on('keyup paste drop blur', '#my_phone_number', function() {
...
});
此处的工作代码示例您应该使用
keyup
而不是keypress
,因为在keypress
上,输入值尚未更改,并且在将新值发布到输入之前应用过滤器。这就是添加新字符的原因
$(document).on('keyup paste drop blur', '#my_phone_number', function() {
...
});
这里的工作代码示例