2013-11-10 61 views
0

我想弄清楚如何onClick按鈕,以便它會自動計算機器在哪一天,並根據它找到網站(例如,如果是星期天,它會找到Sunday.html)想要按鈕onClick getDay網頁

作爲HTML,CSS和Javascript的初學者,我從w3schools獲得了代碼,並將輸出更改爲.html - 顯然,它不起作用。我想知道是否有任何簡單的方法來糾正?

<button onclick="myFunction()">Try it</button> 

<script> 
function myFunction() 
{ 
var d = new Date(); 
var weekday=new Array(7); 
weekday[0]="Sunday.html"; 
weekday[1]="Monday.html"; 
weekday[2]="Tuesday.html"; 
weekday[3]="Wednesday.html"; 
weekday[4]="Thursday.html"; 
weekday[5]="Friday.html"; 
weekday[6]="Saturday.html"; 

var x = document.getElementById("demo"); 
x.innerHTML=weekday[d.getDay()]; 
} 
</script> 

我還做了另外一個方式,通過使用if語句,

if (currentDay == 6) 
{ 
window.location = 'saturday.html'; 
} 
      } 
      else if (currentDay == 0) 
      { 
       window.location = 'sunday.html'; 
      } 

再次,它似乎等不工作。有沒有簡單的方法來做到這一點?

在此先感謝

+0

嘗試'getUTCDay()'如果你有時間區的問題。 –

+0

這不是我遇到問題的時區,更重要的是onClick按鈕不會顯示當天的頁面。 – user2320517

回答

1

對URL做window.location的第二種方法是正確的。

我對你的代碼做了小小的修改。請嘗試小提琴(http://jsfiddle.net/QK2TL/1/)。 打開調試控制檯查看消息。

var d = new Date(); 
var loc = weekday[d.getDay()]; 
alert("about to navigate to " + weekday[d.getDay()]); 
window.location = loc; 
+0

非常感謝! – user2320517

1
function myFunction() 
{ 
var d = new Date(); 
var weekday=[]; 

weekday[0]="Sunday.html"; 
weekday[1]="Monday.html"; 
weekday[2]="Tuesday.html"; 
weekday[3]="Wednesday.html"; 
weekday[4]="Thursday.html"; 
weekday[5]="Friday.html"; 
weekday[6]="Saturday.html"; 

return weekday[d.getDay()]; 
} 


window.location = myFunction(); 
+0

非常感謝! – user2320517