-2

嗨,我有这段代码,任何人都可以知道如何在 2 秒内更改这个随机关键字,

function shuffle(a, b) {
  return Math.random() > 0.5 ? -1 : 1;

}

var keywords = ["<div>1</div>", "<div>2</div>", "<div>3</div>", "<div>4</div>", "<div>5</div>", "<div>6</div>", "<div>7</div>", "<div>8</div>", "<div>9</div>", "<div>10</div>", "<div>11</div>", "<div>22</div>", "<div>44</div>", "<div>32</div>", "<div>46</div>"];
var randomKeywords = keywords.sort(shuffle);


function luckcricket() {
  document.write(randomKeywords);
  alert('laad');
}


luckcricket();

请更正我的代码。在这段代码中,我看不到任何 div 在 2 秒内随机变化

4

3 回答 3

2

您需要添加计时器,

window.setInterval(function() {
// your logic goes here
}, 2000);

每 2 秒你的逻辑就会被执行一次。您可以在此处输入代码以更改随机密钥

更新
应该是这样的

var keywords = ["<div>1</div>", "<div>2</div>", "<div>3</div>", "<div>4</div>", 
        "<div>5</div>", "<div>6</div>", "<div>7</div>", "<div>8</div>", 
        "<div>9</div>", "<div>10</div>", "<div>11</div>", "<div>22</div>", 
        "<div>44</div>", "<div>32</div>", "<div>46</div>"];


function luckcricket() {
    var randomKeywords = keywords.sort(shuffle); 
    document.write(randomKeywords); 
    alert('laad'); 
}

function shuffle(a, b) { 
    return Math.random() > 0.5 ? -1 : 1; 
}

window.setInterval(luckcricket, 2000);
于 2013-02-13T05:17:36.397 回答
0

使用window.setInterval在特定时间后以这种方式重复函数调用:

$(document).ready(function(){
    window.setInterval(function() {
       luckcricket();
    }, 2000);
});

它将每 2 秒调用一次luckcricket()函数。

这是工作演示:http: //jsfiddle.net/5NKXK/

于 2013-02-13T06:02:15.923 回答
0

听起来您希望您的 div 定期洗牌。这不会发生,因为您正在编写randomKeywords,当您调用时它是一个数组luckcricket。您想要做的是从内部调用 shuffleluckcricket()或执行document.write(keywords.sort(shuffle))

function shuffle(a, b) {
  return Math.random() > 0.5 ? -1 : 1;

}

var keywords = ["<div>1</div>", "<div>2</div>", "<div>3</div>", "<div>4</div>", "<div>5</div>", "<div>6</div>", "<div>7</div>", "<div>8</div>", "<div>9</div>", "<div>10</div>", "<div>11</div>", "<div>22</div>", "<div>44</div>", "<div>32</div>", "<div>46</div>"];

function luckcricket() {
    // Shift random keywords into callback so it gets updated EVERY TIME
    var randomKeywords = keywords.sort(shuffle);
    document.write(randomKeywords);

    window.setTimeout( function () {
        // Clear after 1 second
        document.body.innerHTML = '';
    }, 1000);
}


luckcricket();
window.setInterval(luckcricket, 2000);

JSFiddle 示例:http: //jsfiddle.net/rfRzH/

于 2013-02-13T16:35:59.580 回答