简体   繁体   English

警报出现时间过早

[英]Alert appears too early

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

Why is my alert happening before my image is reflected on the page? 为什么在我的图像反映在页面上之前会发生警报?

The jQuery.css() function is asynchronous. jQuery.css()函数是异步的。 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. 创建一个“虚拟”图像以预加载它,并使用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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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