按下按钮时重复功能的动作

时间:2014-10-24 19:50:56

标签: javascript jquery

我试图在javascript / jQuery中重新创建一个来自Treehouse的示例Android应用程序,每次使用" Next Fact"按下按钮,它只能用于下一个随机事实,然后停止。那么每次按下按钮时如何使用新事实刷新它?这是我的js:

 $(document).ready(function(){

  var facts = [
    "Ants stretch when they wake up in the morning.", 
    "Ostriches can run faster than horses.", 
    "Olympic gold medals are actually made mostly of silver.", 
    "You are born with 300 bones; by the time you are an adult you will have 206.", 
    "It takes about 8 minutes for light from the Sun to reach Earth.", 
    "Some bamboo plants can grow almost a meter in just one day.", 
    "The state of Florida is bigger than England.", 
    "Some penguins can leap 2-3 meters out of the water.", 
    "On average, it takes 66 days to form a new habit.", 
    "Mammoths still walked the earth when the Great Pyramid was being built."
   ];

  var fact = facts[Math.round(Math.random() * (facts.length - 1))];

  $("#button").click(function() {
    $("#anotherfact").empty();
    $("#anotherfact").append(fact);
    //Fix me
  });

});

3 个答案:

答案 0 :(得分:1)

每次单击单击处理程序时,您需要重置事实:

将事实移入点击功能:

 $("#button").click(function() {
        var fact = facts[Math.round(Math.random() * (facts.length - 1))];
        $("#anotherfact").empty();
        $("#anotherfact").append(fact);
 });

而不是在页面加载时声明fact一次(这就是为什么你在开始时总是得到一个事实)

答案 1 :(得分:0)

每次单击按钮时选择一个事实,而不是在绑定事件处理程序之前。

即。将var fact = facts[Math.round(Math.random() * (facts.length - 1))];向下移动三行。

答案 2 :(得分:0)

试试这个:

  $("#button").click(function() {
    var fact = facts[Math.round(Math.random() * (facts.length - 1))];
    $("#anotherfact").empty().html(fact);
  });

你需要选择新的事实每次点击!