简体   繁体   中英

Alert appears too early

This is my code in 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);

Why is my alert happening before my image is reflected on the page?

The jQuery.css() function is asynchronous. It will return immediately, so not when the image is loaded.

Create a "dummy" image to preload it and use the onload event to determine when the image is loaded.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM