首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript if/else语句返回一个记录的答案

JavaScript if/else语句返回一个记录的答案
EN

Stack Overflow用户
提问于 2018-06-05 19:03:54
回答 2查看 46关注 0票数 0

我试图在jQuery动画的末尾调用一个函数。该函数在动画之前被调用,并且该函数会得到一个记录的答案。该函数第一次工作得很好,但从第二次开始它会重复一个记录的答案。

代码语言:javascript
复制
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");
});
代码语言:javascript
复制
img{
	width: 150px;
	display: block;
}

.track{
	background: url("https://i.imgur.com/BKL70mT.png") center;
	height: : 100px !important;
	margin-top: 2em;
}

#car_1, #car_2{
	position: relative;
}

#result{
	text-align: center;
	font-size: 3em;
	font-family: arial;
	text-transform: uppercase;
	font-weight: bold;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="track">
  <img src="https://i.imgur.com/ZxAEmIn.png" id="car_1">
  <img src="https://i.imgur.com/nNIg2m4.png" id="car_2">
</div>
<div class="buttons">
  <button id="start">Start</button>
  <button id="reset">Reset</button>
</div>

<p id="result"></p>

EN

Stack Overflow用户

发布于 2018-06-05 19:11:05

有一个原因是每次结果都是重复的。例如,如果第一个"A赢了“,那么你每次都会得到它,因为你没有生成新的随机值。

要做到这一点,你必须在side函数中随机生成。

代码语言:javascript
复制
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);

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

$("#reset").click(function(){
    $("#result").html("");
    $("#car_1").removeAttr("style");
    $("#car_2").removeAttr("style");
});
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50698509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档