gpt4 book ai didi

JavaScript if/else 语句返回并记录答案

转载 作者:行者123 更新时间:2023-12-01 01:59:48 25 4
gpt4 key购买 nike

我试图在 jQuery 动画结束时调用一个函数。该函数在动画之前被调用,并且该函数会给出一个记录的答案。该函数第一次运行得很好,但从第二次开始它就会重复记录的答案。

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");
});
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;
}
<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>

最佳答案

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

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

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");
});

关于JavaScript if/else 语句返回并记录答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com