0

我正在研究自定义时间选择器。我想要做的是:如果用户输入1234它将更改为12:34. 问题是什么都没有发生(我没有得到异常)。这是我到目前为止所拥有的:

// check time entry
(function ($) {
    String.prototype.Timeset = function(){
        return this.replace(/^\d{2}\:\d$/,"$1,");
    }
    $.fn.Time = function(){
        return this.each(function(){
            $(this).val($(this).val().Timeset());
        })
    }
})(jQuery);

HTML 标记:

<input id="txtTime" type="text" maxlength="4" onpaste="return false;" onchange="this.value = this.value.Timeset();" />

我怎样才能做到这一点?我的正则表达式也可能是这个问题的根源。请注意,我不想使用任何外部掩码插件,因为我必须应用hot-keys这个插件。

4

1 回答 1

2

让我们试试这个:

function formatTime(s) {
    return s.replace(/\D/g, "").replace(/^(\d\d)(\d\d).*$/, "$1:$2");
}

(function ($) {
    $.fn.timeInput = function() {
        return $(this).change(function() {
            $(this).val(formatTime($(this).val()))
        });
    }
})(jQuery);

http://jsfiddle.net/LAbFQ/

于 2013-07-11T10:48:47.583 回答