2014-10-20 164 views
1

我試圖用JavaScript生成日曆,當我點擊我的「Volgende」按鈕去下個月我的按鈕被覆蓋。有誰知道如何解決這一問題?JavaScript覆蓋HTML按鈕

的HTML:

<body> 
<button id="Vorige">Vorige</button> <button id="Volgende" onclick="VolgendeFunc()">Volgende</button> 
<br> 
<div id="div"> 
<script type="text/javascript" src="Kal.js"> </script> 
</div> 
</body> 

</html> 

而且這裏的JS:

var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; 
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 
var today = new Date(); 
var dag = today.getDay(); 
var myMonth = today.getMonth(); 
var jaar = today.getFullYear(); 

function VolgendeFunc(){ 
    myMonth = myMonth + 1; 
    Kalender(); 
} 

function Kalender(){ 
document.write(monthNames[myMonth] + jaar + "<br>"); 
    for (var i=1; i <= monthLength[myMonth]; i++){ 
    document.write("<a href='#'>" + i + "</a> "); 
     if (i == 7){ 
     document.write ("<br>"); 
     } 
     if (i == 14){ 
     document.write ("<br>"); 
     } 
     if (i == 21){ 
     document.write ("<br>"); 
     } 
     if (i == 28){ 
     document.write ("<br>"); 
     } 

    } 
} 
window.onload=Kalender(); 
+0

你能描述一下你所說的「當我點擊我的‘Volgende’按鈕轉到下個月我的按鍵會被覆蓋」是什麼意思? – Termato 2014-10-20 18:06:00

+3

可能是'document.write'是你當前問題的根源。另外,有時二月有29天。 – 2014-10-20 18:06:40

+0

將「Volgende」按鈕視爲NextMonth按鈕 – Niek 2014-10-20 18:22:17

回答

2

文件撰寫立即替換你可能在頁面的任何HTML。

相反,添加一些像一個誘惑變種,然後將HTML推到。

一會兒,我會在這裏添加一個jsfiddle來向你展示。

你的代碼有一些其他問題......但這會讓你超過第一個問題。

UPDATED EXAMPLE

var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; 
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 
var today = new Date(); 
var dag = today.getDay(); 
var myMonth = today.getMonth(); 
var jaar = today.getFullYear(); 

var VolgendeFunc = function(){ 
    myMonth = myMonth + 1; 
    Kalender(); 
} 

var BackFunc = function(){ 
    myMonth = myMonth -1; 
    Kalender(); 
} 

function Kalender(){ 
    var myHTML =''; 
    myHTML+=monthNames[myMonth] + jaar + "<br>"; 
    for (var i=1; i <= monthLength[myMonth]; i++) 
    { 
     myHTML+="<a href='#'>" + i + "</a> "; 
     if (i%7 == 0) { myHTML += "<br>"; } //Save you some lines (best practice) 
    } 

    document.getElementById('div').innerHTML = myHTML; 
} 

document.addEventListener("DOMContentLoaded", Kalender, false); 
+1

@termato感謝您的編輯。 :) – 2014-10-20 18:37:20

+0

非常感謝你們! – Niek 2014-10-20 18:42:07

+1

接受答案是正確的,這是說謝謝的最好方式。 ;-) – 2014-10-20 18:43:15