2016-04-28 6 views
0

ボタンのクリックに基づいて動作する配列内のオブジェクトの値に基づいて、ランダムな文生成プログラムを作成しました。私が理解できないことは、ボタンをクリックするたびに新しい文を作成する方法です。 ボタンをクリックして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); 
}); 

Codepen

+1

をあなたのクリックファンクション内のボタンメソッドの上に3行移動します。 – fix

答えて

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); 
}); 
+0

ああ、ありがとう!私は明らかに勉強しているだけです。 – lowbelly

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); 
    }); 
+0

それは、ありがとう! – lowbelly

1

2つのもの:

01出力に
  • id参照は、余分なスペースを持っている

    $( '#出力 ').empty()===> $(' #出力')、空();

  • あなたはjQueryの

  • から書類の準備を使用したい場合があり、記載された他の回答のように、あなたがクリック可能なアクション

ここで、クイックテストでランダム呼び出し必要があります。

<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> 
関連する問題