2016-10-08 6 views
0

私はwindow.onload関数を持つスイッチケースを持っています。ここでJavascript Switch Case Error with window.onload

はコードです:これが動作しない理由を

window.onload = ButtonClicked(); 

function ButtonClicked() { 
    document.getElementById("Easy").onclick = alertMessage(); 
    document.getElementById("Intermediate").onclick = alertMessage(); 
    document.getElementById("Advanced").onclick = alertMessage(); 
} 
function alertMessage() { 
    switch(this.id) { 
     case "Easy": 
      alert("Easy Content.") 
     break; 
     case "Intermediate": 
      alert("Intermediate Content.") 
     break; 
     case "Advanced": 
      alert("Advanced Content.") 
     break; 
    default: 

    } 
} 

誰でも知っていますか?私はしばらくこの問題を解決しようとしてきましたが、それを修正する方法はまだ分かりません。 window.onloadの部分が機能しないのですか?それとも関数を呼び出さないのでしょうか?または、switchのケースが機能していませんか?

+2

、それを割り当てない:ここでは

は動作するコードです。 – rlemon

+1

'window.onload = ButtonClicked()の代わりに' window.onload = ButtonClicked; 'を試してみてください。 – knutesten

答えて

0

リスナーをDOM要素に設定するときは、かっこは使用できません(場合によっては例外を除く)。 window.onload = ButtonClicked;window.onload = ButtonClicked();を意味します。ButtonClicked()は関数の名前(関数への参照)であり、ButtonClickedは関数の呼び出し(つまり実行)のためです。同じ推論がonclickリスナーのためになされるかもしれません。あなたがメソッドを呼び出している

window.onload = ButtonClicked; 
function ButtonClicked() { 
    document.getElementById("Easy").onclick = alertMessage; 
    document.getElementById("Intermediate").onclick = alertMessage; 
    document.getElementById("Advanced").onclick = alertMessage; 
} 

function alertMessage() { 
    switch (this.id) { 
    case "Easy": 
     alert("Easy Content."); 
     console.log("Easy Content"); 
     break; 
    case "Intermediate": 
     alert("Intermediate Content."); 
     console.log("Intermediate Content"); 
     break; 
    case "Advanced": 
     alert("Advanced Content."); 
     console.log("Advaced Content"); 
     break; 
    default: 
    } 
}