2014-12-17 4 views
1

매일 새로 고쳐야 할 필요가 없도록 페이지를 새로 고칠 날짜를 얻으려고합니다. 이 코드는 제 위치에 있지만 작동하지 않는 것 같습니다. 날짜가 표시되지만 날짜가 변경되면 업데이트되지 않습니다. 참고로, 이것은 BrightSign 디스플레이에서 사용됩니다. 아무도 내가 뭘 잘못하고 있다고 말할 수 있습니까? 내가 그렇게 아무것도 너무 복잡 자바 스크립트 초보자 :)의 종류 해요날짜를 자동 새로 고침하는 방법?

<script type="text/javascript"> 
<!-- 
function clockTick() { 
    currentTime = new Date(); 
    month = currentTime.getMonth() + 1; 
    day = currentTime.getDate(); 
    year = currentTime.getFullYear(); 
    setInterval(clockTick, 1000); 
    return (month + "/" + day + "/" + year); 
} 
document.write(clockTick()); 
//--> 
</script> 
+1

[먼저 document.write를 사용하지 마십시오. (http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad- 연습), 두 번째, setTimeout 또는 setInterval에 대해 알아보기 – epascarello

+0

날짜를 새로 고치려면 간격으로 폴링하고 실제로 날짜가 바뀌면 실제로 변경해야합니다. 너가 원하는게 그거야 ? – adeneo

답변

0

이 시도 할 수 있습니다 : 외부에서 clockTick()를 호출합니다.

function clockTick() { 
 
     currentTime = new Date(); 
 
     month = currentTime.getMonth() + 1; 
 
     day = currentTime.getDate(); 
 
     year = currentTime.getFullYear(); 
 
     // alert("hi"); 
 
     document.getElementById('date').innerHTML=month + "/" + day + "/" + year; 
 
    } 
 
    
 
    setInterval(function(){clockTick();}, 1000);//setInterval(clockTick, 1000); will also work
<div id="date"></div>

1

는 매 초마다 새로 고쳐 있도록 함수 밖으로 setInterval을하고 함수 내부 페이지의 시간을 설정하는 것이 좋습니다 :

function clockTick() { 
 
    var currentTime = new Date(), 
 
     month = currentTime.getMonth() + 1, 
 
     day = currentTime.getDate(), 
 
     year = currentTime.getFullYear(), 
 
     hours = currentTime.getHours(), 
 
     minutes = currentTime.getMinutes(), 
 
     seconds = currentTime.getSeconds(), 
 
     text = (month + "/" + day + "/" + year + ' ' + hours + ':' + minutes + ':' + seconds); 
 
    // here we get the element with the id of "date" and change the content to the text variable we made above 
 
    document.getElementById('date').innerHTML = text; 
 
} 
 

 
// here we run the clockTick function every 1000ms (1 second) 
 
setInterval(clockTick, 1000);
<span id="date"></span>

+0

감사합니다! 이것은 잘 작동했습니다. –

+0

만족 스러우면 답을 자유롭게 선택하십시오. = P – Tomanow

관련 문제