[英]Adding selected number of divs inside another div
林試圖創建一個應用程序,將擲骰子數量由用戶決定。 我希望每個骰子都位於單獨的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);
}
但這似乎不起作用。 也許我使用錯誤的方法。
小錯字-使用document.getElementById('dice').appendChild(div)
而不是div.getElementById('dice').appendChild(div)
。
function addDice() { var div = document.createElement('div'); div.innerHTML = "<p> here will be a dice</p>"; document.getElementById('dice').appendChild(div); }
<div id="diceTable"> <button onclick="addDice()">Add Dice</button> </div> <div id='dice'></div>
這直接來自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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.