【问题标题】:Value from input in quotes javascript引号中输入的值 javascript
【发布时间】:2013-06-12 16:52:01
【问题描述】:

如果我有这样的代码,带有引号和作者,我怎样才能得到两个 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

【问题讨论】:

  • 尽量避免使用document.write
  • 是否允许用勺子喂食?
  • @AtifMohammedAmeenuddin :由于 OP 正在学习 JS ,我认为这是允许的 :) 但我在这里可能是错的
  • @harsha 你能写一些快速的例子吗? :)
  • 您想用authors数组中的名称替换字符串中的(randomuser)

标签: javascript input quotes


【解决方案1】:

我认为您想将引号数组中的 (randomuser) 替换为从几个 &lt;input&gt; 标记中获得的字符串。在这种情况下,您可以像这样获取这些输入的内容:

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 example

编辑

要从较大的列表中随机选择一个报价,您可以将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 循环,但我会让你自己弄清楚。

【讨论】:

  • 如果我有一个包含 100 个报价和 5 个用户的列表,我该怎么做?:) 感谢您的回答!
  • 为你编辑了答案。
  • 谢谢!!! jsfiddle.net/mvp9U/1 为什么总是显示在 div 中的第二个引号? ;o
  • 您定义了数组两次,而不是用两个元素定义它。这里是a fixed example,见第 1 行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 2013-06-07
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
相关资源
最近更新 更多