我正在完成一项任务,我必须编写10个随机句子,然后我必须创建文本字段。这些文本字段应该包含我在句子中放入的任何内容。我需要帮助处理包含句子内部单词的代码吗?
我的HTML是:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Assignment 4</title>
<h1> Assignment 4 - Sample Solution </h1>
</head>
<body>
<p>
Name: <input type="text" id = "input" size="10" />
<br />
Verb Phrase: <input type="text" id = "input2" size="10" />
<br />
Adjective: <input type="text" id = "input3" size="10" />
<br />
Noun: <input type="text" id = "input4" size="10" />
<br />
HOW MANY SENTENCES? <select id = "numOfSentences" size = "1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<button id = "displaySilly">
Display Silly
</button>
<p id = "output"></p>
<script src = "silly.js"></script>
</body>
</html>
我的javascript是
var names = ["Alice","Rowena","Carol","David","Erin"];
var verbs = ["jumped on", "ran from", "scolded", "yelled at","talked to"];
var adjs = ["yellow","big","smelly","hairy","bad"];
var nouns = ["bear","tree","rock","student","instructor"];
// variables for the sentence components
var name, verb, adj, noun;
// display silly sentences
document.getElementById('displaySilly').onclick = function() {
// get number of sentences from drop down
var numOfSentences =
document.getElementById('numOfSentences').value;
//convert to integer
numOfSentences = parseInt(numOfSentences);
// initialize results string
var results = "";
// create required number of silly sentences
for (var i = 1 ; i <= numOfSentences ; i++) {
//pick components at random from arrays
name =
names[Math.floor(Math.random() * names.length)];
verb =
verbs[Math.floor(Math.random() * verbs.length)];
adj =
adjs[Math.floor(Math.random() * adjs.length)];
noun =
nouns[Math.floor(Math.random() * nouns.length)];
// concatenate to form a sentence
// add to other sentences
results = results + name + " " + verb +
" the " + adj + " " + noun +
".<br />";
}
// display the silly sentences
document.getElementById('output').innerHTML = results;
} //*** END onclick handler
谢谢
答案 0 :(得分:0)
names.push(document.getElementById('input').value)
这会将名称中的值推送到数组中。您将需要为每个数组和输入执行此操作。
您需要在代码的随机化器部分之前执行此操作。