如果我有这样的代码,带有引号和作者,我如何获得两个 input type="text"
框,我可以在其中写入例如两个名称,然后将名称显示到用引号代替“(随机用户)”?
//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
最佳答案
我认为您想用从几个 <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.
编辑:
要从较大的列表中随机选择报价,您需要更改 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 循环,但我会让您自行解决。
关于javascript - 来自引号 javascript 中输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17071056/