在另一个div中添加选定数量的div

时间:2017-03-13 21:39:39

标签: javascript html

我正在尝试创建一个可以滚动用户决定的骰子数量的应用。 我希望每个骰子都在一个单独的div中,但我很难实现将div插入HTML的代码。

作为一个测试,我创建了一个按钮,将一个div插入另一个div,这是我到目前为止所得到的:

<div id="diceTable">
    <button onclick="addDice()">Add Dice</button>
</div>

JS是:

function addDice(){
var div = document.createElement('div');

div.innerHTML = "<p> here will be a dice</p>";

div.getElementById('dice').appendChild(div);
}

但它似乎没有用。也许我使用了错误的方法。

2 个答案:

答案 0 :(得分:2)

小错字 - 使用document.getElementById('dice').appendChild(div)代替div.getElementById('dice').appendChild(div)

&#13;
&#13;
function addDice() {
  var div = document.createElement('div');
  div.innerHTML = "<p> here will be a dice</p>";
  document.getElementById('dice').appendChild(div);
}
&#13;
<div id="diceTable">
  <button onclick="addDice()">Add Dice</button>
</div>
<div id='dice'></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这直接来自W3C学校https://www.w3schools.com/jsref/dom_obj_div.asp

<script>
function myFunction() {
    var x = document.createElement("DIV");
    var t = document.createTextNode("This is a div element.");
    x.setAttribute("style", "background-color: pink;");
    x.appendChild(t);
    document.body.appendChild(x);
}
</script>

使用append.child而不是innerHTML

相关问题