值从输入的引号javascript
Value from input in quotes javascript
本文关键字:javascript 输入 更新时间:2023-09-26
如果我有这样的代码,带引号和作者,我怎么能得到两个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)"answers"(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循环,但我将留给您自己解决。
相关文章:
- 我怎样才能得到“__类型“;用javascript输入json
- 如何获取javascript输入并在html中调用它
- JavaScript - 输入按钮隐藏 - 不起作用
- 选中复选框时启用Javascript输入类型,未选中复选框则禁用
- JavaScript-输入不是数字时提示
- Javascript:输入框-自动大写第一个字母,但可以重写
- Javascript输入格式
- 来自键盘的JavaScript输入没有“prompt()”方法弹出窗口(如Pascal Readln或GWiBasic输
- JavaScript 输入值问题
- Javascript输入更改
- Javascript输入问题
- JavaScript 输入字段不可编辑
- 动态生成的 Javascript 输入字段无法被 Httpservletrequest 识别???仅在 Chrome 中
- JavaScript 输入标签未设置 ID 或类
- JavaScript 输入字段验证
- 如何使用 javascript 输入 2 个框
- 直接从Javascript输入/传递图像到输入类型=“文件名”
- 如何显示双引号以通过javascript输入
- HTML5/Javascript 输入只读状态在 IOS 上使用 XCode 滑动
- Javascript 输入到 HTML 表单 onSubmit 与 # 操作到 PHP $_GET(同一文件上的所有代码