带有setInterval的Javascript createElement

时间:2014-05-15 10:02:15

标签: javascript html setinterval createelement

所以我在尝试完成一项小任务时遇到了一些问题,而且我现在还有点困难。

我正在创建一个应用程序,当我点击一个按钮时,应用程序在setInterval循环中创建带有createElement的div,在1秒内(大约50 Ms)多达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(框)递增。像这样:box1(1),box2(2),box3(3)等......

有关此问题的任何想法,提示或帮助吗?

非常感谢帮助!

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:3)

尝试this demo

<强> HTML

<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/

答案 2 :(得分:0)

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);
}

答案 3 :(得分:0)

function makeNew() {

  var box = document.createElement("div");
  var boxText = document.createTextNode(counter);
  box.appendChild(boxText);

  document.body.appendChild(box);

        counter++;
}