Javascript createElement with setInterval



所以我有一些小问题,我试图完成一个小任务,我有点卡在这一点上。

我正在制作一个应用程序,当我点击一个按钮时,应用程序在setInterval循环中使用createElement创建div,在1秒内(大约50毫秒)创建多达20个div。我也可以停止间隔,然后重新开始。这将创建一个20px X 20px的小红色框。下面是代码:

<script>    
    var box;
    var counter = 0;
    function makeNew() {
        document.body.appendChild(
            document.createElement('box'));
                counter++;
                document.getElementById('boks').innerHTML = counter;
    }
    function startInterval() {
        box = setInterval(function () { lagNy() }, 50);
    }
    function stoppInterval() {
        clearInterval(box);
    }
</script>
<body>
    <input type="button" id="start" value="Generer" onclick="startInterval();" /> 
    <input type="button" id="stopp" value="Stopp" onclick="stoppInterval();" />
</body>

我实际上需要帮助的是,我想要在这些div中打印数字,并且它随着每个创建的div (box)而增加。像这样:box1(1), box2(2), box3(3)等....

有什么想法、技巧或帮助吗?

非常感谢帮助!

试试这个演示。

<input type="button" id="start" value="Generer" onclick="startInterval();" />
<input type="button" id="stopp" value="Stopp" onclick="stoppInterval();" />
<p id="boks"></p>

JS

var timer,
    counter = 0;
function makeNew() {
    document.body.appendChild( document.createElement('div') );
    counter++;
    document.getElementById('boks').innerHTML += 'box('+counter+'),';
}
function startInterval() {
    timer = setInterval(makeNew, 50);
}
function stoppInterval() {
    clearInterval(timer);
}

更新:看看你的问题可能是你想要得到这个http://jsfiddle.net/aamir/84HgL/2/

保持对元素的引用。附加您想要的文本。

counter++;
var box = document.createElement('div'); // Use a real HTML element
box.appendChild(
    document.createTextNode(counter)
);
document.body.appendChild(box);

http://jsfiddle.net/Cs49D/

var box;
var counter = 0;
function makeNew() {
    counter++;
    var new_box = document.createElement('div');
    new_box.setAttribute("class", "box");
    new_box.innerHTML = counter;
    document.body.appendChild(new_box);
}
function startInterval() {
    box = setInterval(function () { makeNew() }, 50); 
}
function stoppInterval() {
    clearInterval(box);
}
function makeNew() {
  var box = document.createElement("div");
  var boxText = document.createTextNode(counter);
  box.appendChild(boxText);
  document.body.appendChild(box);
        counter++;
}

最新更新