Javascript使用循环舍入值的函数..回调?

时间:2014-02-25 03:33:47

标签: javascript jquery loops if-statement callback

有2个HTML下拉列表,一个用于12小时的时间,一个用于每小时5分钟的间隔...

..
<select class="form-control" name="hour" id="hour">
  <option>1</option>
  ..
  <option>12</option>
</select>
..
<select class="form-control" name="minute" id="minute">
  <option>0</option>
  ..
  <option>55</option>
</select>
..

一直在尝试使用if / elseif在另一个函数内部编写一个javascript函数(这样做),但它需要帮助..可能是回调函数还是匿名函数? < / p>

var hours = date.getHours();
var minutes = date.getMinutes();

function hour(hours)
{
    // account for 24-hour clock
    if (hours > 12)
    {
        hours = hours - 12
    };

    // account for 0 in 24
    else if (hours == 0)
    {
        hours = 12
    };
}

// round to the 5minute marks
if (minutes >= 0 && minutes < 3) {minutes = 0};
else if (minutes >= 3 && minutes < 8) {minutes = 5};
..
else if (minutes >= 53 && minutes < 58) {minutes = 55};

// round 58/59/60 to the next hour
else (minutes >= 58 && minutes < 60) {minutes = 0 && hours = hours + 1};

// apply the rounded numbers
$('#hour').val(hours);
$('#minute').val(minutes);

1 个答案:

答案 0 :(得分:0)

提示:更好的方法来舍入分钟而不是很多if / else if:

var offset=minutes%5;
if(offset < 3) minutes=minutes-offset;
if(offset >=3) minutes = minutes+(5-offset);
if(minutes==60){
   minutes=0;hours+=1;
}