每按一下按钮,创建一个新的随机句子

时间:2016-04-28 15:52:04

标签: javascript jquery

我已经成功制作了一个随机句子生成器,它基于数组中的对象值,该对象基于单击按钮而工作。我无法弄清楚如何在每次点击按钮时创建一个新句子。 似乎我可以在单击按钮时清除#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);
});

Codepen

3 个答案:

答案 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);
   });