6

我们遇到了 jQuery UI 微调器的问题。当我们在微调器上设置一个最大值时,使用微调器按钮是不可能超过这个最大值的。但是使用键盘我们可以转到任何数字。

http://jsfiddle.net/Uygt2/

我们还需要允许用户使用键盘。jQuery UI 中是否有针对此问题的标准解决方案?

正如您在此(http://jsfiddle.net/Uygt2/4/)中看到的 Rab Nawaz 更新的小提琴,blur总是被调用,这导致我们的逻辑运行两次。

4

3 回答 3

13

编辑:处理负数。感谢Rzassar指出这一点。

您可以使用 oninput 事件:{ 'keyup paste'用于不支持它的旧浏览器}

演示 jsFiddle

$("input").spinner({
    max: 10,
    min: -10
}).on('input', function () {
    if ($(this).data('onInputPrevented')) return;
    var val = this.value,
        $this = $(this),
        max = $this.spinner('option', 'max'),
        min = $this.spinner('option', 'min');
    // We want only number, no alpha. 
    // We set it to previous default value.         
    if (!val.match(/^[+-]?[\d]{0,}$/)) val = $(this).data('defaultValue');
    this.value = val > max ? max : val < min ? min : val;
}).on('keydown', function (e) {
    // we set default value for spinner.
    if (!$(this).data('defaultValue')) $(this).data('defaultValue', this.value);
    // To handle backspace
    $(this).data('onInputPrevented', e.which === 8 ? true : false);
});
于 2013-05-31T12:04:57.977 回答
0

仅供参考,我自己想出了这个解决方案:

    $("input").spinner({
        stop: function (event, ui) {
            $(this).change();
        }
    }).change(function () {

        // min/max calculations
        callFunction();

    });

这似乎工作正常,但roasted' 的答案看起来更好。

于 2013-05-31T12:26:22.827 回答
0

我知道我错过了这艘船,但是对于按照您需要的方式运行的独立微调器,您可以使用该spinchange事件 -

$('input').spinner({
    min: 0,
    max: 3,
    page: 10,
    change: function(event, ui){

        var value = this.value
            min = this.min,
            max = this.max;

        if (!value.match(/^\d+$/)){ // Value is non-numerical

            /** Set the value to the previous value */
            value = 0 

        } else { // Value is numerical

            /** Check that value falls within min and max range */
            if(value > max){
                value = max;
            } else if(value < min){
                value = min;
            }

        }

        /** Send the correct value to the spinner (if it needs changing) */
        if(value !== this.value){
            $(this).spinner("value", value);
        }

    }
});
于 2013-10-31T15:16:10.747 回答