使用Javascript动态创建具有递增ID的dom元素

Wil*_*iam 4 javascript dom

我有一个ID为"orangeButton"的div,每次点击它都会创建一个新的div.这工作正常,但...我希望每个新创建的div都有一个增加的数字添加到它的ID.

我不知道该怎么做.

这是我到目前为止的评论的代码.

http://jsfiddle.net/taoist/yPrab/1/

谢谢

Javascript代码

   var applicationArea = document.getElementById("applicationArea");
    var orangeButton = document.getElementById("orangeButton");


    orangeButton.onclick = function() {
      var newDivThingy = document.createElement("div");
      newDivThingy.id  = 'newDivThingy';  // I want each newly created div to have a      numeric value concatenated to it's ID. IE newDivThingy1 newDivThingy2 newDivThingy3
      applicationArea.appendChild(newDivThingy);


    };?
Run Code Online (Sandbox Code Playgroud)

bak*_*kal 8

我错过了什么,为什么不使用柜台?

var counter = 0;
button.onclick = function(){
   var newDivThingy = document.createElement("div");
   newDivThingy.id  = 'newDivThingy' + (++counter);
   // continue your stuff here     
}
Run Code Online (Sandbox Code Playgroud)

  • 我尝试使用不同的方法来创建计数器,但无法找出正确的语法。我决定问问而不是浪费时间。 (2认同)