使用JavaScript在电话字段中放置破折号的最佳方法是什么?

时间:2015-05-06 08:01:28

标签: javascript html

使用JavaScript在电话字段中放置破折号的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

使用它,也许,它太复杂了,但是这样的代码可以工作(这里使用了http://www.jstorage.info/):

function addPhoneListener(element) {
if (!(element instanceof jQuery)) {
    element = $('#' + element.id);
}
var maxLength = 20;
var firstDashIndex = 5;
var secondDashIndex = 9;
var thirdDashIndex = 12;
save('hasPreviousEnded', 'false');
function process() {
    var clearPhone = element.val().replaceAll('-', '');
    var length = clearPhone.length;
    if (!/^\d+$/.test(clearPhone) || length > maxLength) {
        element.val(length > 0 ? element.val().substring(0, maxLength) : '');
    }
    function placeDashes(array) {
        if (element.val() !== '-'
            && !isEmpty(element.val())) {
            for (var i = 0; i < array.length; i++) {
                if (!equals(element.val().charAt(array[i]), '-')
                    && element.val().length >= array[i]) {
                    element.val(element.val().substring(0, array[i]) + '-' + element.val().substring(array[i],
                        element.val().length));
                }
            }
        }
        if (element.val().length >= maxLength && element.val().charAt(element.val().length - 1) === '-') {
            element.val(element.val().substring(0, element.val().length - 1));
        }
    }

    if (Number(saved('previousDashPlacing')) + 85 < new Date().getTime()) {
        placeDashes([firstDashIndex, secondDashIndex, thirdDashIndex]);
        save('previousDashPlacing', new Date().getTime());
    }
}

process();
element.on('keyup', function () {
    process();
})

 function save(key, data) {
    if (typeof data === 'object') {
        data = toJSON(data);
    }
    $.jStorage.set(key, data, null);
 }
}