我试图在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>
发布于 2018-06-05 19:11:05
有一个原因是每次结果都是重复的。例如,如果第一个"A赢了“,那么你每次都会得到它,因为你没有生成新的随机值。
要做到这一点,你必须在side函数中随机生成。
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");
});https://stackoverflow.com/questions/50698509
复制相似问题