1

我有一个功能:

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 。

任何帮助表示赞赏,谢谢

4

1 回答 1

1

您应该使用keyup而不是keypress,因为keypress输入的值尚未更改,并且您在将新值发布到输入之前应用过滤器。这就是添加新字符的原因。

$(document).on('keyup paste drop blur', '#my_phone_number', function() {
    ...
});

此处的工作代码示例http://jsbin.com/upinux/1/edit

于 2013-05-17T19:59:39.360 回答