javascript - 尝试创建一个可重用的函数并将结果显示在 div 中

标签 javascript jquery html

我正在尝试使用这个功能。我想做的就是将天、小时、分钟和秒的值放入 .overTime div 中。我想一遍又一遍地使用相同的函数,因为我有更多的 div,我想在其中显示相同的值,但以不同的方式。

你们太棒了,谢谢。

    NowTime = new Date(); //Time Now
StartTime = new Date($('#StartTime').val());
StopTime = new Date($('#StopTime').val());

function fixIntegers(integer){
    if (integer < 0)
        integer = 0;
    if (integer < 10)
        return '0' + integer;
    return '' + integer;
}  
    function Test( difference )
    {
        var toReturn = { days: 0, hours: 0, minutes: 0, seconds: 0 };
        toReturn.seconds = fixIntegers(difference % 60);
        difference = Math.floor(difference / 60);    

        toReturn.minutes = fixIntegers(difference % 60);
        difference = Math.floor(difference / 60);

        toReturn.hours = fixIntegers(difference % 24);
        difference = Math.floor(difference / 24);

        toReturn.days = fixIntegers(difference);
        return toReturn;
    }

    function run()
    {
        var output = Test( Math.floor( ( NowTime - StopTime ) / 1000 ) );
        $('.OverTime').html( output.days + ':' + output.hours + ':' + output.minutes + ':' + seconds);
    }
setInterval(run, 1000)

fiddle :http://jsfiddle.net/8943U/47/

最佳答案

您的第一个问题是:

$('.OverTime').html( output.days + ':' + output.hours + ':' + output.minutes + ':' + seconds);

应该是:

$('.OverTime').html( output.days + ':' + output.hours + ':' + output.minutes + ':' + output.seconds);

变量 seconds 不存在,您需要 output.seconds 代替。然后你的函数将开始工作see here .

你的第二个问题是这些值是 NaN,我将让你来解决这个问题。

干杯!

关于javascript - 尝试创建一个可重用的函数并将结果显示在 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085227/

相关文章:

javascript - 拆分 URL 和查询字符串

html - 向右浮动第二个元素而不指定第一个元素的宽度?

c# - ASP.NET - Razor 从模型中获取图像

JavaScript 回调说明

javascript - 如何选择串联名称

javascript - 从仅包含发送的查询的数组中排除结果。 MongoDB

javascript - Express 和 Nodejs : Best way to call an external API

jquery - 使用jQuery限制列表元素的数量

jquery - 我想从 html 使用 jquery 中排除一些类,例如 $ ('html' ).not ('.classname' ),但它不起作用?

css - 如何在绝对位置和相对位置之间对齐 div