如何控制document.write写入的位置

时间:2013-01-16 23:01:21

标签: javascript

我想让我的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>");

4 个答案:

答案 0 :(得分:8)

为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>";

答案 1 :(得分:2)

您应该使用选择器来获取div并将其写为innerHtml属性:

document.getElementById("yourDivsId").innerHTML=quotes[index];

答案 2 :(得分:2)

您可以使用:

document.getElementById("divID").innerHTML=quotes[index];

或者您可以使用JQuery

$("#divID").html(quotes[index]);

答案 3 :(得分:2)

document.write将准确写出它的位置。 document.write最终没有条件目标。但是,您正在寻找的是一些DOM操作。

您应该定位div,然后将文本放在那里:

HTML

<div id="divId"></div>

JS

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);

var mydiv = document.getElementById("divId");
mydiv.innerHTML = '<p>' +  quotes[index] + '</p>';