1

引用符と作成者を含むこのようなコードがある場合、input type="text"たとえば 2 つの名前を書き込むことができる 2 つのボックスを取得し、"(random user)" の代わりに名前を引用符に表示するにはどうすればよいですか?

//store the quotations in arrays
quotes = [];

authors = [];

quotes[0] = "(randomuser) example (randomuser) example?";

authors[0] = "Authors!";

quotes[1] = "(random user) example (random user) example?";

authors[1] = "Authors!";

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

//display the quotation

document.write("<DL>\n");

document.write("<DT>" + "\"" + quotes[index] + "\"\n");

document.write("<DD>" + " " + authors[index] + "\n");

document.write("</DL>\n");

//done
4

1 に答える 1

0

<input>引用符配列の (randomuser) を、いくつかのタグから取得した文字列に置き換えたいと思います。その場合、次のようにこれらの入力の内容を取得できます。

var user1 = document.getElementById("input1").value;
var user2 = document.getElementById("input2").value;

String.replace()これで、次のように、を使用して入力値を "(randomuser1)" と "(randomuser2)" に置き換えることができます。

//Sub in the usernames
var newquote = quotes[0].replace("(randomuser1)", user1); //quotes[0] can of course be any index
newquote = newquote.replace("(randomuser2)", user2);

そして、あなたは表示することができますnewquote。を避ける必要があることに注意してくださいdocument.write()。代わりに、次のように、ページに表示 div を作成して、その中に引用符を入れることができます。

var quotediv = document.getElementById("quoteDiv"); //get the div (or any other element) that you want to display the quote in
quotediv.innerHTML = newquote; //display your quote in the div.

JsFiddle の例

編集

より大きなリストから引用をランダムに選択するには、次のquotes[0]ように変更しますquotes[Math.floor(Math.random() * quotes.length)]。ユーザーをさらに追加するには、入力と置換ステートメントを追加します。例:

//Sub in the usernames
var ind = Math.floor(Math.random() * quotes.length); //select random quote
var newquote = quotes[ind].replace("(randomuser1)", user1);
newquote = newquote.replace("(randomuser2)", user2);
newquote = newquote.replace("(randomuser3)", user3);
newquote = newquote.replace("(randomuser4)", user4);
newquote = newquote.replace("(randomuser5)", user5);

これは、より多くのユーザー向けの for ループに単純化できますが、それについては理解しておいてください。

于 2013-06-12T17:53:16.153 に答える