警报出现时间过早

时间:2018-11-09 11:14:15

标签: javascript

这是我的JavaScript代码:

$("#bot1Selected").attr("card-value", botPick.value + botPick.suit.substring(0, 1));
$("#bot1Selected").css("background-image", "url('images/cards/" + checkValue(botPick.value) + botPick.suit.substring(0, 1) + ".png')");


$("#player1Selected").attr("card-value", playerDisplay);
$("#player1Selected").css("background-image", "url('images/cards/" + checkValue(playerDisplay.slice(0, -1)) + playerDisplay[playerDisplay.length - 1] + ".png')");

if (playerVal.value > botPick.value) {
    //sleep(500);
    alert("Your Card is Higher");
} else {
    //sleep(500);
    alert("Bot's Card is Higher");
}

if (playerVal.value > botPick.value) {
    endTurn(playerDiscard, [playerVal, botPick]);
} else {
    endTurn(bot1Discard, [playerVal, botPick]);
}

$("#playerDiscard").text(playerDiscard.length);
$("#playerDraw").text(player.length);

为什么我的警报发生在我的图像反映在页面上之前?

1 个答案:

答案 0 :(得分:0)

jQuery.css()函数是异步的。它会立即返回,因此加载图像时不会返回。

创建一个“虚拟”图像以预加载它,并使用onload事件来确定何时加载该图像。

jQuery(document).ready(function() {
    var imgUrl = "https://via.placeholder.com/350x150";
    var $img = $("<img />");
    $img.on("load", function() {
        $("#yourImage").css("background-image", "url("+ imgUrl +")");
        alert("image is loaded");
    });
    $img.attr("src", imgUrl);
});