Could someone explain why this document.write overwrites the entire page?

杀马特。学长 韩版系。学妹 提交于 2019-12-12 01:03:23

问题


Here is the code; javascript

function Roll()
     // Results: displays a randomly selected image of a 6-sided die
     {
       var roll;

       roll = RandomInt(1, 6);

       if (roll == 1) {
         document.getElementById("die").src = 
             "die1.gif";
         document.write("<center><p><a href='bad.html'> Enter </a></p></center>");
       }
       else if (roll == 2) {
         document.getElementById("die").src = 
             "die2.gif";
         document.write("<center><p><a href='good.html'> Enter </a></p></center>");
       }
       else if (roll == 3) {
         document.getElementById("die").src = 
             "die3.gif";
         document.write("<center><p><a href='bad.html'> Enter </a></p></center>");
       }
       else if (roll == 4) {
         document.getElementById("die").src = 
             "die4.gif";
         document.write("<center><p><a href='good.html'> Enter </a></p></center>");
       }
       else if (roll == 5) {
         document.getElementById("die").src = 
             "die5.gif";
         document.write("<center><p><a href='bad.html'> Enter </a></p></center>");
       }
       else {
         document.getElementById("die").src = 
             "die6.gif";
         document.write("<center><p><a href='good.html'> Enter </a></p></center>");
       }
     }

And here is the Jsfiddle http://jsfiddle.net/seymorevenue/TcNF7/ (though document.write doesn't seem to work there, and the dice images arn't up) I don't think I really understand the Document.write statement, and is there a better method? All I want to do is roll a die and display a link based on the result. Thanks for any help


回答1:


I think document.write() makes significant changes to a website and it is rarely used after clicking on a button, but rather when a site loads.

Instead, use something like this:

document.getElementByID('YourOutputDiv').innerHTML = 'Text to display on website';


来源:https://stackoverflow.com/questions/16094162/could-someone-explain-why-this-document-write-overwrites-the-entire-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!