我正在尝试制作一个随机句子生成器,在适当的位置随机抽取形容词、名词和动词。
第一次,它完美地生成了句子,并给出了再次生成的按钮。但当我单击此按钮时,什么也没有发生。我不知道为什么。
如果在第一代中,在第一次单击按钮时,将句子简单地添加到已有的内容上,并且按钮上的文本更改为“生成另一个”而不是“生成一个句子”,那就更好了。 ”然后,当您再次单击该按钮时,句子应该会自动更改。
如果有人可以研究我的代码并帮助我,那就太好了,谢谢:
var nouns = ["girl", "boy", "man", "woman", "animal"];
var adjectives = ["giant", "tiny", "funny", "sad", "strange"];
var verbs = ["jumping", "running", "smiling", "exploding", "dying"];
document.write(
"Welcome to the Useless Random Sentence Generator! More words and combinations will be added in the future. You can always email liorpoliti24@gmail.com for verb, noun, and adjective suggestions as well as other suggestions to make this generator better. Click the button to begin."
);
function randIndex() {
var randIndex = Math.floor(Math.random() * 5);
var noun = nouns[randIndex];
var adjective = adjectives[randIndex];
var verb = verbs[randIndex];
var result = "The " + adjective + " " + noun + " is " + verb + ".";
document.write(result);
elem = document.createElement("hr");
elem.setAttribute("width", "500px");
elem.setAttribute("legth", "8000px");
document.body.appendChild(elem);
const btn = document.createElement("button");
btn.innerText = "Generate Another";
document.body.appendChild(btn);
btn.innerText = "Generate Another";
btn.addEventListener("click", () => {
randIndex();
});
}
<button onclick="randIndex();">
Generate Random Sentence
</button>
最佳答案
这有效:
var nouns = ["girl", "boy", "man", "woman", "animal"];
var adjectives = ["giant", "tiny", "funny", "sad", "strange"];
var verbs = ["jumping", "running", "smiling", "exploding", "dying"];
function randIndex() {
var randIndex = Math.floor(Math.random() * 5);
var noun = nouns[randIndex];
var adjective = adjectives[randIndex];
var verb = verbs[randIndex];
var result = "The " + adjective + " " + noun + " is " + verb + "."
var li = document.createElement("li");
li.innerHTML = result;
document.getElementById("result").appendChild(li);
document.getElementById("generateButton").value = "Generate another";
}
<div>
"Welcome to the Useless Random Sentence Generator! More words and combinations will be added in the future. You can always email liorpoliti24@gmail.com for verb, noun, and adjective suggestions as well as other suggestions to make this generator better. Click the button to begin."
</div>
<ul id="result"></ul>
<input type="button" id="generateButton" onclick="randIndex();" value="Generate Random Sentence" />
关于javascript - 如何使用 onclick 按钮重新调用生成函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61148919/