<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 ループに単純化できますが、それについては理解しておいてください。