为twodimensional数组的每个元素提供一个html ID

时间:2015-11-03 16:34:57

标签: javascript html css arrays

如何为我的二维数组的每个元素添加正在进行的html ID,以便通过css访问每个元素?

https://jsfiddle.net/jc22Lopj/3/

var list = document.getElementById('werk'),
li = document.createElement('li'),
clone;
werk.forEach(function (item) {
clone = li.cloneNode();
clone.textContent = item;
clone.className = "item"; 
list.appendChild(clone);
});

我想用一个数组实现以下结构:

werk = [
[TextBla1,TextBla2],
[TextBla3,TextBla4]
 ]

<ol id="werk">
<li class="item">
<div id="text1">TextBla1</div>
<div id="text2">TextBla2</div>
</li>
<li class="item">
<div id="text3">TextBla3</div>
<div id="text4">TextBla4</div>
</li>
</ol>

我知道我可以访问以下每个元素,但我不知道如何为每个元素提供特定的ID。

var list = document.getElementById('werk'),
li = document.createElement('li'),
clone;
werk.forEach(function (item) {
clone = li.cloneNode();
clone.textContent = item;
clone.className = "item"; 
list.appendChild(clone);

for (var i = 0; i < item.length; i++) {
  alert(item[i]); ???
}

});

1 个答案:

答案 0 :(得分:0)

只需添加另一个forEach,因为item是您的文本数组

var werk = [["Text1","Text2"],["Text3","Text4"]],
    list = document.getElementById('werk')

werk.forEach(function (item) {
    var clone = document.createElement('li');
    clone.className = "item"; 

    item.forEach(function(text) {
        var div = document.createElement('div');
        div.setAttribute("id", text);
        div.textContent = text;
        clone.appendChild(div);
    });

    list.appendChild(clone);
});