尝试使用setTimeout创建一个小延迟,但它不起作用

时间:2014-02-16 18:28:10

标签: jquery jquery-ui events settimeout

我有一些像这样的jQuery / JavaScript:

$("#dialog-coin-flip").dialog({
    height: "auto",
    width: 400,
    autoOpen: false,
    modal: false,
    draggable: true,
    resizable: true,
    closeOnEscape: false,
    closeText: "Close",
    buttons: {
        "Flip": function() {
            $(this).children("div").html("Flipping...");
            var flipResult = coinFlip();
            setTimeout($(this).children("div").html(flipResult), 1000);
        },
        "Close": function() {
            $(this).dialog("close");
        },
    }
});

function coinFlip() {
    var flipResult = Math.floor(Math.random() * (1 - 0 + 1) + 0);
    if (flipResult === 0) {
        return "You flipped a coin and it came up heads.";
    }
    else if (flipResult === 1) {
        return "You flipped a coin and it came up tails.";
    } 
}

当我点击“Flip”按钮时,我收到消息:

Uncaught SyntaxError: Unexpected identifier

在1000毫秒过后,在Chrome的JavaScript控制台中。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您需要在代码中包含代码 试着用这个:

var $here = $(this);
setTimeout(function() { 
    $here.children("div").html(flipResult); 
}, 1000);

而不是:

setTimeout($(this).children("div").html(flipResult), 1000);
相关问题