2015-04-07 41 views
0
$(document).ready(function() { 
    function currentDate() { 
    var now = new Date(); 
    var year = now.getFullYear(); 
    var month = now.getMonth(); 
    var day = now.getDay(); 
    var hours = now.getHours(); 
    var minutes = now.getMinutes(); 
    var seconds = now.getSeconds(); 

    var time = hours + ":" + minutes + ":" + seconds; 
    var date = (day + "/" + month + "/" + year).toLocaleDateString(); 

    $('#time').html("<span class='glyphicon glyphicon-time'></span> " + time); 
    $('#date').html("<span class='glyphicon glyphicon-calendar'></span> " + date); 

    } 
    currentDate(); 
    setInterval(currentDate(), 1000); 
}); 

此代码似乎没有做任何事情......没有错误... 它已被链接在'头部'。jQuery日期和时间不修改HTML文档

<script src="js/datetime.js"></script> 

我的元素是:

<div class="navbar-right" style="color:#fff;margin-right:0px;"> 
    <div class="navbar-brand" id="fade"> 
     <p id="date" title="Your Date."></p> 
    </div> 
    <div class="navbar-brand" id="fade"> 
     <p id="time" title="Your Time."></p> 
    </div> 
</div> 

的网页似乎并没有显示任何东西,都在它应该去的地方。

回答

0

.toLocaleDateString()不能仅与日期字符串一起使用。 .toLocaleDateString()可以添加到新的Date()中。如果您使用setInterval,则该函数必须在没有括号的情况下调用。

function currentDate() { 
    var now = new Date(); 
    var year = now.getFullYear(); 
    var month = now.getMonth(); 
    var day = now.getDay(); 
    var hours = now.getHours(); 

    var minutes = now.getMinutes(); 
    minutes = (minutes < 10) ? '0'+minutes : minutes; 

    var seconds = now.getSeconds(); 
    seconds = (seconds < 10) ? '0'+seconds : seconds; 

    var time = hours + ":" + minutes + ":" + seconds; 
    var date = (day + "/" + month + "/" + year); 

    $('#time').html("<span class='glyphicon glyphicon-time'></span> " + time); 
    $('#date').html("<span class='glyphicon glyphicon-calendar'></span> " + date); 

} 
$(function() { 
    currentDate(); 
    setInterval(currentDate, 1000); 
}); 

您确定js/datetime.js是您的文件的正确路径。尝试使用HTML内的代码:)

+0

请不要发布唯一代码的答案。请解释你的答案。 – phts

+0

我用一些解释编辑我的帖子 –

0

1)

setInterval应采取函数的变量。但在你的情况下,你称之为函数。应该没有大括号:

setInterval(currentDate, 1000); 

2)

您有重复的ID id="fade"。使用唯一的ID。