如何在动态创建的div中显示?

时间:2016-01-10 16:13:13

标签: javascript html

HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script type="text/javascript" src="forWordsGame.js"></script>
    <style>
    div#board{
        background:#CCC;
        border:#999 1px solid;
        position:absolute;
        width:90%;
        height:540px;
        padding:20px;
        margin:20px, auto;
        position:relative;
    }


    div#guessing{
        background: red;
        border:#000 1px solid;

        width:121px;
        height:51px;
        float:center;

        margin: 30px;
    }
    div#wordsToGuessWrapper{
        background: green;
        border:#000 1px solid;
        position:relative;
        width:80%;
        height:200px;
        float:center;
        margin: 30px;
    }
    div#wordsToGuessWrapper > div{
        background: red;
        border:#000 1px solid;
        width:71px;
        height:71px;
        float:left;
        margin:50px;
        padding:20px;
        font-size:20px;
        cursor:pointer;
        text-align:center;
    }

    </style>

    </head>
    <body>
        <input id="myButton" type="button" value="Start game" />
        <div id="board">
            <div id="guessing">Guessing</div>
                <div id="wordsToGuessWrapper">

                </div>
        </div>
    </body>
    </html>

的Javascript

for (var i = 0; i < myFourWordsArray.length; i++) {
  // output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+myFourWordsArray[i]+'\')"></div>';
  output += '<div id="tile_' + i + '"  " value="' + myFourWordsArray[i] + ' "   onclick="init1()"></div>';
}
document.getElementById('wordsToGuessWrapper').innerHTML = output;


[].forEach.call(document.getElementsByTagName('div.wordsToGuessWrapper'), function(div, i) {
  div.textContent = myFourWordsArray[i];
});

请告诉我如何将数组myFourWordsArray中的值放入动态创建的div中。当我查看站点代码但不在每个div中时,会出现数组myFourWordsArray中的值。我需要为四个动态创建的div中的每一个创建一个值。

1 个答案:

答案 0 :(得分:0)

这是一个如何迭代数组并将其添加到HTML元素的示例。您可以看到实时示例here

var arr = ['apple', 'banana', 'cherry', 'durian']
var section = document.querySelector('section')
arr.forEach(function (fruit) {
  var div = document.createElement('div')
  div.classList.add('my-class')
  div.textContent = fruit
  section.appendChild(div)
})

在您的情况下,您会使用类似document.querySelector('div#wordsToGuessWrapper')

的内容