用对象数组中的内容创建div?

时间:2015-10-09 06:22:21

标签: javascript html

所以我有:

arrayofobj = [
    {
        property: "string",   // "card" object with different data types
        property2: integer
    },
    {
        property: "string",   // "card" object with different data types
        property2: integer
    },
    {
        //etc more cards
    }
];

var playDeck = arrayofobj.slice(0);//creates copy of deck to "use" for game
shuffled(playDeck);//shuffles deck
playerHand = [];//empty array to save cards into
deal10(playDeck);//removes the 1st 10 out of playDeck and puts in playerHand

现在从被引入playerHand的10个,我试图在屏幕上显示它们。我设置了field

<div id="playerHand"></div>

我的尝试并不是很成功:

for (var i = 0; i < playerHand.length; i++) {
    content = playerHand[i];
    x = document.getElementById('playerHand').appendChild(document.createElement('div'));
    x.className = 'card' + [i];
    document.getElementsByClassName('card' + [i]).textContent = content;
}

我未能达到预期的效果。就编程而言,我是初学者,所以我愿意接受建设性的批评。所以如果你还没有收集到我想要做的就是在屏幕上显示每个对象或card作为它自己的div(这样我就可以为它们添加点击处理程序并让点击的对象在屏幕...例如。)

1 个答案:

答案 0 :(得分:2)

我认为主要问题是getElementsByClassName,它返回一个数组,而不是对元素的实际引用。见下文:

var data, content, container, element;

container = document.getElementById('container');
data = [
    {
        name: "stringa"
    },
    {
        name: "stringb"
    }
];


for (var i = 0; i < data.length; i++) {
    // Are you accessing an actual property in your code? It seems
    // you are just referencing the whole object.
    content = data[ i ].name;

    // Just save the createElement reference ;)
    element = document.createElement('div');

    // Why are you appending [i] instead of i directly?
    element.className = 'card' + i;

    // By saving the element directly we don't have to query for
    // the class in this step. The other problem was probably that
    // `getElementsByClassName` returns an array, so you would have
    // to call:                                      vvv
    // document.getElementsByClassName('card' + [i])[ 0 ]
    element.textContent = content;

    container.appendChild( element );
}

强制性的JSFiddle:http://jsfiddle.net/tgtefsrm/1/