这对我来说似乎很荒谬.我应该使用数组还是有其他更好的解决方案?
$('.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;
}
});
Run Code Online (Sandbox Code Playgroud)
if($(this).val().length == 1) {
$(this).val('0' + $(this).val());
}
Run Code Online (Sandbox Code Playgroud)
或者只是在页面加载时用零填充所有单个数字,而不是onchange:
$('.hoursRange option').filter(function() {
return $(this).val().length == 1;
}).each(function() {
$(this).val('0' + $(this).val());
});
Run Code Online (Sandbox Code Playgroud)
只需使用正则表达式:
$(this).val($(this).val().replace(/^[0-7]$/, "0$&"));
Run Code Online (Sandbox Code Playgroud)