问题
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