Javascript if else语句返回记录的答案

时间:2018-06-05 11:03:54

标签: javascript jquery

我试图在jquery动画结束时调用一个函数。该函数在动画之前被调用,并且函数会出现记录的答案。该功能第一次完美地工作,但从第二次起,它重复记录的答案。 小提琴link

var random_1 = Math.floor((Math.random() * 1000) + 200);
var random_2 = Math.floor((Math.random() * 1000) + 200);

function result(){

    if (random_1 > random_2) {
        $("#result").html("A won");
        return;
    }

    else {
        $("#result").html("b won")
    }
}

$("#start").click(function(){
    $("#car_1").animate({"left":screen.width - 150},random_1,result());
    $("#car_2").animate({"left":screen.width - 150},random_2);
});

$("#reset").click(function(){
    $("#result").html("");
    $("#car_1").removeAttr("style");
    $("#car_2").removeAttr("style");
});

2 个答案:

答案 0 :(得分:1)

每次重复结果都有一个原因。就像第一次“赢了”一样,你每次都会得到它,因为你没有产生新的随机值。

要做到这一点,你必须在副功能中获得随机生成。

{{1}}

答案 1 :(得分:1)

您可以将所有内容放在“开始”点击处理程序中,如下所示:

$(document).ready(function(){
  $("#start").click(function(){
    var random_1 = Math.floor((Math.random() * 1000) + 200);
    var random_2 = Math.floor((Math.random() * 1000) + 200);
    console.log("A: "+random_1);
    console.log("B: "+random_2);

    if (random_1 > random_2) {
      $("#result").html("A won");
        return;
    }else{
      $("#result").html("b won")
    }

    $("#car_1").animate({"left":screen.width - 150},random_1);
    $("#car_2").animate({"left":screen.width - 150},random_2);
  });

  $("#reset").click(function(){
      $("#result").html("");
      $("#car_1").removeAttr("style");
      $("#car_2").removeAttr("style");
  });
});
img{
  position:relative;
  left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button> <button id="reset">Reset</button><br>
<div id="result"></div>
<img id="car_1" src="http://www.iconsplace.com/icons/preview/orange/car-256.png"><br>
<img id="car_2" src="https://www.iconsdb.com/icons/preview/red/car-xxl.png"><br>

正如评论中提到的,您的问题是在页面加载时仅创建一次随机数。现在每个“开始”点击都会有新的数字进行比较。

现在,在这里获胜的人是数量较多的人......但是那个看起来更慢的人也是如此!我会颠倒那种逻辑(在条件下)。 ;)

相关问题