我已经成功制作了一个随机句子生成器,它基于数组中的对象值,该对象基于单击按钮而工作。我无法弄清楚如何在每次点击按钮时创建一个新句子。 似乎我可以在单击按钮时清除#output的内容,并且randomWord()将再次运行但没有骰子。
var words = {
noun : ['mouse','bird','cat','dog'],
verb : ['runs','sleeps','explodes','flies'],
place : ['house', 'space station', 'car', 'office']
};
var container = document.getElementById('output');
function print(sentence){
container.innerHTML = sentence;
}
var noun;
var verb;
var place;
var word;
var sentence;
var button;
function randomWord( type ){
rando = Math.floor(Math.random() * words[type].length);
word = words[type][rando];
return word;
}
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
$('button').click(function(){
$('#output ').empty();
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>";
print(sentence);
});
答案 0 :(得分:1)
每次单击按钮时都需要更新随机变量,目前您在脚本初始化期间执行过一次:
$('button').click(function(){
$('#output ').empty();
//generate new random words on click
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>";
print(sentence);
});
答案 1 :(得分:1)
有几件事:
id对输出的引用有一个额外的空间
$('#output')。empty()===&gt; $( '#输出')空();
您可能希望使用jQuery中的Document Ready
在这里快速测试:
<html>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" ></script>
<script>
$( document ).ready(function() {
var words = {
noun : ['mouse','bird','cat','dog'],
verb : ['runs','sleeps','explodes','flies'],
place : ['house', 'space station', 'car', 'office']
};
var container = document.getElementById('output');
function print(sentence){
container.innerHTML = sentence;
}
var noun;
var verb;
var place;
var word;
var sentence;
var button;
function randomWord( type ){
rando = Math.floor(Math.random() * words[type].length);
word = words[type][rando];
return word;
}
$('#button').click(function(){
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
$('#output').empty();
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ". </p>";
print(sentence);
});
});
</script>
<div id="output"></div>
<button id="button">click</button>
</html>
答案 2 :(得分:0)
也许你只需要尝试:
$('button').click(function(){
noun = randomWord('noun');
verb = randomWord('verb');
place = randomWord('place');
var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>";
print(sentence);
});