2014-09-05 91 views
0

低於我的HTML代碼應該調用從列表中3分隨機的話,但它不是HTML代碼不工作

<html> 
<body> 
     <div id="placeholder"></div> 
     <input id="clickMe" type="button" value="Generate!" onclick="generator();" /> 

     <script> 
     function generator(){ 
    var begin = ["Example1","Example2"] 
    var middle = ["moreexamples","moreandmore"] 
    var end = ["moremoremore","evenmoreman"] 

    // Random numbers are made 
    var randomNumber1 = parseInt(Math.random() * begin.length); 
    var randomNumber2 = parseInt(Math.random() * middle.length); 
    var randomNumber3 = parseInt(Math.random() * end.length); 
    var name = begin[randomNumber1] + "" + middle[randomNumber2] + "" + end[randomnumber3];   

    //If there's already a name it is removed 
    if(document.getElementById("result")){ 
    document.getElementById("placeholder").removeChild(document.getElementById("result")); 
    } 
    var element = document.createElement("div"); 
    element.setAttribute("id", "result"); 
    element.appendChild(document.createTextNode(name)); 
    document.getElementById("placeholder").appendChild(element); 
} 

     </script> 
     <script> 
     if(document.getElementById("result")){ 
    document.getElementById("placeholder").removeChild(document.getElementById("result")); 
} 

element = document.createElement("div"); 
element.setAttribute("id", "result"); 
element.appendChild(document.createTextNode(name)); 
document.getElementById("placeholder").appendChild(element); 
</script> 
     </div> 

</body> 
</html> 

如果有人知道什麼是錯了,請告訴我如何解決它。 :) 順便說一句,這只是一個頁面,我會稍後裝飾它。

+0

不碰撞的工作? – 2014-09-05 23:47:36

回答

3

這是因爲您的randomNumber3變量被錯誤地引用爲randomnumber3

聲明:var randomNumber3 = parseInt(Math.random() * end.length);

用法:var name = begin[randomNumber1] + "" + middle[randomNumber2] + "" + end[randomnumber3];

退房的小提琴here

+0

非常感謝!我從來沒有見過! – 2014-09-05 23:50:24

+3

@免費商業谷歌控制檯是你的朋友:)。節省我的培根很多次! – mattytommo 2014-09-05 23:50:54