【问题标题】:Javascript Function for rounding values using a Loop.. Callback?使用循环舍入值的Javascript函数..回调?
【发布时间】:2014-02-25 03:33:46
【问题描述】:

有 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 函数来舍入值,但它需要帮助。也许是回调函数或匿名函数?

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);

【问题讨论】:

标签: javascript jquery loops if-statement callback


【解决方案1】:

提示:舍入分钟数而不是大量 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;
}

【讨论】:

    猜你喜欢
    • 2016-12-17
    • 2017-06-02
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多