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

以下を使用できます。

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 に答える
2

セレクターを使用して div を取得し、その innerHtml プロパティを記述する必要があります。

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

于 2013-01-16T23:03:52.380 に答える