ボタンのクリックに基づいて動作する配列内のオブジェクトの値に基づいて、ランダムな文生成プログラムを作成しました。私が理解できないことは、ボタンをクリックするたびに新しい文を作成する方法です。 ボタンをクリックしてrandomWord()を実行しただけで、サイコロを実行しないと#outputの内容をクリアできるようです。ボタンを1回クリックするごとに新しいランダム文章が作成される
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