使用Javascript动态创建dom元素增加ID [英] Using Javascript to dynamically create dom elements with incrementing ID's
本文介绍了使用Javascript动态创建dom元素增加ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ID为orangeButton的div,每次点击它都会创建一个新的div。这样做很好,但是...我想要每个新创建的div都添加一个增量编号。
我不知道该怎么做。 >
这是一个小编,我至今已经有了意见。
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'; //我想要每个新创建的div具有连接到它的ID的数字值。 IE newDivThingy1 newDivThingy2 newDivThingy3
applicationArea.appendChild(newDivThingy);
};
解决方案
我缺少一些东西,为什么不使用计数器?
var counter = 0;
button.onclick = function(){
var newDivThingy = document.createElement(div);
newDivThingy.id ='newDivThingy'+(++ counter);
//继续你的东西
}
I have a div with an ID "orangeButton" and each time you click on it it creates a new div. This works fine but... I want each newly created div to have an incremental number added to it's ID.
I am not sure how to do this.
Here is a fiddle of the code I have thus far with comments.
http://jsfiddle.net/taoist/yPrab/1/
Thank you
Javascript Code
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);
};
解决方案
Am I missing something, why not use a counter?
var counter = 0;
button.onclick = function(){
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy' + (++counter);
// continue your stuff here
}
这篇关于使用Javascript动态创建dom元素增加ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文