我已经成功地根据数组中基于点击按钮的对象值创建了一个随机语句生成器。我无法弄清楚的是,如何在每次点击按钮时创建一个新句子。 似乎我可以只清除#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);
});
在您的点击功能中移动按钮方法上方的3行。 – fix