如何以更简单,更荒谬的方式写这个

时间:2011-01-12 08:49:03

标签: javascript jquery

这对我来说似乎很荒谬。我应该使用数组还是有其他更好的解决方案?

$('.hoursRange').change(function() {
    if ('0' == $(this).val())
    {
        $(this).val('00');
        return false;
    }
    if ('1' == $(this).val())
    {
        $(this).val('01');
        return false;
    }
    if ('2' == $(this).val())
    {
        $(this).val('02');
        return false;
    }
    if ('3' == $(this).val())
    {
        $(this).val('03');
        return false;
    }
    if ('4' == $(this).val())
    {
        $(this).val('04');
        return false;
    }
    if ('5' == $(this).val())
    {
        $(this).val('05');
        return false;
    }
    if ('6' == $(this).val())
    {
        $(this).val('06');
        return false;
    }
    if ('7' == $(this).val())
    {
        $(this).val('07');
        return false;
    }
});

8 个答案:

答案 0 :(得分:6)

if($(this).val().length == 1) {
    $(this).val('0' + $(this).val());
}

或者只是在页面加载时用零填充所有单个数字,而不是onchange:

$('.hoursRange option').filter(function() {
    return $(this).val().length == 1;
}).each(function() { 
    $(this).val('0' + $(this).val());
});

演示:http://jsfiddle.net/WKdWq/

答案 1 :(得分:5)

只需使用正则表达式:

$(this).val($(this).val().replace(/^[0-7]$/, "0$&"));

答案 2 :(得分:1)

$(this).val('0' + $(this).val());

答案 3 :(得分:1)

var value = $(this).val();
if ($(this).val().length < 2) {
   $(this).val('0' + value);
}

答案 4 :(得分:1)

$('.hoursRange').change(function() {
   if (parseInt($(this).val(),10)<10) $(this).val("0"+parseInt($(this).val(),10));
}

答案 5 :(得分:1)

this answer提供了零填充功能。使用它,你可以简单地做:

$('.hoursRange').change(function() {
    $(this).val( zerofill($(this).val(), 2) );
}

答案 6 :(得分:0)

我不是jQuery的专家,但它很尴尬。 我会检查边界条件(0<=$(this).val()<=7),如果不符合则返回false。否则

var v = $(this).val();
v='0'+v;
$(this).val(v);

答案 7 :(得分:0)

$('.hoursRange').change(function() {
    $(this).val( $(this).val().replace(/(\b\d\b)/,'0$1') );
}

我在这里看不到你需要任何条件语句或额外昂贵的jQuery调用。