从 for 循环中显示数组内容

Display array content from a for-loop

我正在尝试显示 randomTable 中的一个数字 8 秒,1by1。可悲的是它根本没有显示任何东西。

    var numberTable = [];
    var randomTable = [];

    $('#pooling').append('<div id="box"> </div>');

    for (var i=1;i<=32;i++) {
        numberTable.push(i);
    }

    for (var i=0;i<8;i++) {
        (function (e) {
            randomTable.push(1 + Math.floor(Math.random() * (32 - e)));
            numberTable.splice(e,1);
            $('#box').replaceWith('<div id = "box>' + randomTable[e] + '</div>');
            $('#box').show(0).delay(8000).hide(0);
        })(i);
    }

当我删除第二个 for 循环时,它显示空的#box,但是对于这个循环,它根本不会创建这个 div。可能是什么问题?

首先 - replaceWith 调用中缺少 "

second - 使用这种方法你应该总是只得到一个 div (id=box) 因为你在每次迭代中使用 replaceWith 覆盖它 - 你可以使用追加和后缀 id像这样:

$('#box').append('<div id="box-' + e '">' + randomTable[e] + '</div>')

或者完全保留 id 并使用 class 代替 - 顾名思义 - 文档中应该只有一个具有相同 ID 的元素。

提供您的 html 标记愿望,如果这个不合适。

不太清楚你的意图是什么,但也许这会有所帮助:

var numberTable = [];
var randomTable = [];
for (var i = 1; i <= 32; i++) {
  numberTable.push(i);
}
for (var i = 0; i < 8; i++) {
  randomTable.push(1 + Math.floor(Math.random() * (32 - i)));
  numberTable.splice(i, 1);
}
console.log("randomTable: " + randomTable);

$('#box').text(randomTable[0]);
var x = 1;
function repeat(){
  window.setTimeout(function(){
    if (x < 8) {
      $('#box').text(randomTable[x]);
      x++;
      repeat();
    }
  },8000);
};
repeat();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="box"></p>