重载几次后,时间和日期消失

时间:2013-06-25 08:00:39

标签: javascript jquery html jquery-mobile

Javascript / jQuery / jQuery Mobile

下面的代码工作正常但是当我重新加载/ F5此页面的几次时,currentDate和currentTime值会消失。然后,当我再次重新加载几次时,它的工作正常。有谁知道原因是什么以及如何解决?

 <%@ include file="/common/taglibs.jsp"%>
<%@ include file="/common/jquery-mobile-javascript-css.jspf"%>
<%@ include file="/common/jquery-mobile-javascript.jspf"%>
<!DOCTYPE html> 

     <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script type="text/javascript">
            <script type="text/javascript">
                jQuery.noConflict();
                jQuery(document).ready(function() { 
                    function DisplayTime(){
                        if (!document.all && !document.getElementById)
                            return
                        var timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2;
                        var CurrentDate=new Date();
                        var hours=CurrentDate.getHours();
                        var minutes=CurrentDate.getMinutes();
                        var seconds=CurrentDate.getSeconds();
                        var year=CurrentDate.getYear();

                        if (hours<=9) {
                            hours="0"+hours;
                        }

                        if (minutes<=9) {
                            minutes="0"+minutes;
                        }

                        if (seconds<=9) {
                            seconds="0"+seconds;
                        }

                        if(year < 1000){
                            year += 1900;
                        }

                        var currentTime=hours+":"+minutes+":"+seconds;
                        var currentDate=dayNames[CurrentDate.getDay()]+' '+monthNames[CurrentDate.getMonth()]+' '+CurrentDate.getDate()+', '+year;
                        document.getElementById('curDate').innerHTML="<font style='font-size:18px;font-weight:bold;'>"+currentDate+" </b>";
                        timeElement.innerHTML="<font style='font-size:18px;font-weight:bold;'>"+currentTime+"</b>";
                        setTimeout(DisplayTime,1000);
                    }
                    window.onload=DisplayTime;
            </script>
        </head>

HTML

    <body>
        <div id="page" data-role="page">
    <div data-role="header" data-theme="b" data-position="fixed">
        <p  class="ui-li-aside"><span id=curDate></span><span id=curTime></span></p>
    </div>
    </div>       
</body>

1 个答案:

答案 0 :(得分:0)

最后,我已使用标志替换window.onload=DisplayTime;,例如:

if(flag==true){
                DisplayTime();
                flag=false;
            }

我认为window.onload是在Displaytime完全加载之前的早期响应,这就是为什么它在重载/刷新页面多次后不会显示在页面上