1

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

4 回答 4

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>";
于 2013-01-16T23:04:19.173 回答
2

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

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

于 2013-01-16T23:03:52.380 回答
2

您可以使用:

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

或者你可以使用 JQuery

$("#divID").html(quotes[index]);
于 2013-01-16T23:05:16.797 回答
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>';
于 2013-01-16T23:05:58.283 回答