我想让我的JavaScript从数组中打印出随机报价。我设法做到了,但是不知道如何控制它的写位置。我希望在div中编写它。救命?

码:

quotes = [];
quotes[0] = "I have a new philosophy. I'm only going to dread one day at a time.";
quotes[1] = "Reality is the leading cause of stress for those in touch with it.";
quotes[2] = "Few things are harder to put up with than the annoyance of a good example.";
quotes[3] = "The pure and simple truth is rarely pure and never simple.";
quotes[4] = "There's no business like show business, but there are several businesses like accounting.";
quotes[5] = "Man invented language to satisfy his deep need to complain.";

//calculate a random index
index = Math.floor(Math.random() * quotes.length);

//display the quotation
document.write("<p>" +  quotes[index] + "</p>");

最佳答案

给div一个ID,说divid,然后使用document.getElementById()获取div,然后使用innerHTML设置其内容;

quotes = [];
quotes[0] = "I have a new philosophy. I'm only going to dread one day at a time.";
quotes[1] = "Reality is the leading cause of stress for those in touch with it.";
quotes[2] = "Few things are harder to put up with than the annoyance of a good example.";
quotes[3] = "The pure and simple truth is rarely pure and never simple.";
quotes[4] = "There's no business like show business, but there are several businesses like accounting.";
quotes[5] = "Man invented language to satisfy his deep need to complain.";

//calculate a random index
index = Math.floor(Math.random() * quotes.length);

//display the quotation
document.getElementById('divid').innerHTML = "<p>" +  quotes[index] + "</p>";

关于javascript - 如何控制document.write写入的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14369474/

10-11 20:07
查看更多