我认为您想将引号数组中的 (randomuser) 替换为从几个<input>
标签中获得的字符串。在这种情况下,您可以像这样获取这些输入的内容:
var user1 = document.getElementById("input1").value;
var user2 = document.getElementById("input2").value;
现在,您可以使用 "(randomuser1)" 和 "(randomuser2)" 替换那些输入的值String.replace()
,如下所示:
//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 循环,但我会让你弄清楚这一点。