Javascript 将用户输入值传递给随机文本字符串
我正在尝试创建一个主题生成器。我想将用户输入值传递到一个句子中。例如,我希望用户给我一个关键字,比如Dog,然后我希望用户输入作为变量传递给一个随机的文本字符串。清洁狗的五大方法 以下是我目前拥有的:Javascript 将用户输入值传递给随机文本字符串,javascript,html,input,Javascript,Html,Input,我正在尝试创建一个主题生成器。我想将用户输入值传递到一个句子中。例如,我希望用户给我一个关键字,比如Dog,然后我希望用户输入作为变量传递给一个随机的文本字符串。清洁狗的五大方法 以下是我目前拥有的: var randomStrings = [ "Top 5 Ways To insert user input here ", "hello 2", "hello 3", "hello 4", "hello 5", "hello A", "he
var randomStrings = [
"Top 5 Ways To insert user input here ",
"hello 2",
"hello 3",
"hello 4",
"hello 5",
"hello A",
"hello B",
"hello C",
"hello D",
"hello E" // Note: No comma after last entry
];
function RndMsg() {
var msg = randomStrings[Math.floor(Math.random()*randomStrings.length)];
document.getElementById('randomDiv').innerHTML = msg;
}
HTML如下所示:
<form action="" method="post" onsubmit="return false">
<h2>Select a keyword to optimize for</h2>
<input placeholder="Keyword" type="text" id="keyword" name="user-input" required="">
<input class="button" type="button" value="Generate" name="sessionid" onclick="RndMsg()"/>
</form>
<div >
<p id="randomDiv"></p>
</div>
请参阅下面的更新代码 var随机字符串=[ 在此处插入用户输入的前5种方法, 你好2,, 你好3,, 您好4,, 你好,5号, A你好, 你好,B, 你好,C, 你好,D, hello E//注意:最后一项后没有逗号 ]; 函数RndMsg{ var msg=randomStrings[Math.floorMath.random*randomStrings.length]; var newMsg=; $.eachrandomStrings,functioni,str{ 如果str==msg{ newMsg=str+'+$'关键字'.val; 随机字符串[i]=newMsg; 返回false; } }; document.getElementById'randomDiv'.innerHTML=newMsg; } 选择要优化的关键字
这就是我要做的
<form action="" method="post" onsubmit="return false">
<h2>Select a keyword to optimize for</h2>
<input placeholder="Keyword" type="text" id="keyword" name="user-input" required="">
<input class="button" type="button" value="Generate" name="sessionid" id="generate"/>
</form>
<div >
<p id="randomDiv"></p>
</div>
希望这有帮助 哇,谢谢,部分有效。出于某种原因,它在一些随机字符串上多次添加关键字。我会在一个时刻做一个小提琴肯定,你期待的关键字不被复制在随机字符串?我想有关键字输出只使用一次,每个随机字符串,如果可能的话。我开始理解如何使用您的代码,但它比我在W3C上读到的要复杂得多
var randomStrings = [ //random string to attach to
"Top 5 Ways To",
"hello 2",
"hello 3",
"hello 4",
"hello 5",
"hello A",
"hello B",
"hello C",
"hello D",
"hello E" // Note: No comma after last entry
];
var generate = document.getElementById('generate'); // grab the button from the html
//when the button is clicked do this function
generate.onclick= function () {
//since the keyword can change, get it every time the user clicks generate and he gets a new topic
var keyword = document.getElementById('keyword').value;
var msg = randomStrings[Math.floor(Math.random()*randomStrings.length)];
//when inserting data written by the user into the page DO NOT USE INNERHTML! they can insert code here! use text content instead.
document.getElementById('randomDiv').textContent = msg + " " + keyword;
}