jQuery .each()中的SetInterval

jef*_*lte 4 javascript jquery function

我希望迭代一组div并随机执行一些随机操作.我试图使用以下函数,但console.log在每次迭代时返回相同的对象和整数.执行以下操作的正确方法是什么?

    $('.cloud').each(function() {
    $cloud = $(this);
    ranNum = Math.floor(Math.random() * 5000);
    setInterval(function() {
        setTimeout("console.log($cloud + ranNum)", ranNum)
    })
})          
Run Code Online (Sandbox Code Playgroud)

Rob*_*nik 9

使用本地(闭包)变量 var

因为您将功能作为字符串提供,所以必须使用全局变量.您的代码应该使用在事件匿名函数闭包中定义的局部变量编写,如下所示:

$('.cloud').each(function() {
    var $cloud = $(this);
    var ranNum = Math.floor(Math.random() * 5000);
    setInterval(function() {
        // $cloud won't have any particular meaning though
        console.log($cloud + ranNum);
    }, ranNum);
});
Run Code Online (Sandbox Code Playgroud)

不寻常的组合setIntervalsetTimeout

另外,我没有看到你使用间隔和超时的原因?用一个.可能是间隔,因为你想要重复执行某些东西.