我正在尝试创建一个主题生成器。我想将用户输入值传递到句子中。例如,我希望用户给我一个像 Dog 这样的关键字,然后我希望该用户输入作为变量传递给随机文本字符串。 例如:清洁狗的 5 种最佳方法
这是我目前拥有的:
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 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)];
var newMsg= '';
$.each(randomStrings, function(i, str){
if (str === msg){
newMsg = str + ' ' + $('#keyword').val();
randomStrings[i] = newMsg;
return false;
}
});
document.getElementById('randomDiv').innerHTML = newMsg;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>
关于javascript - 将用户输入值传递给随机文本字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975999/