开发者

How to write this in a simpler less ridiculous way

This just seems absurd to me. Should I use array instead or is there some other better solution?

$('.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' == $(thi开发者_开发知识库s).val())
    {
        $(this).val('06');
        return false;
    }
    if ('7' == $(this).val())
    {
        $(this).val('07');
        return false;
    }
});


Just use a regex:

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


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

Or just pad all of the single digits with zeros on page load, rather than onchange:

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

Demo: http://jsfiddle.net/WKdWq/


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


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


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


A function for zero-padding is available from this answer. Using that, you can simply do:

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


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

I don't see you needing any conditional statements or additional expensive jQuery calls in here.


I am not an expert on jQuery but it is awkward. I would check boundary condition (0<=$(this).val()<=7) and if not met return false. Otherwise

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜