gpt4 book ai didi

javascript - only one root element is allowed 动态创建div时出错

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:52 25 4
gpt4 key购买 nike

这是我的代码:

function AddDivs() {
var MainDiv = document.createElement('div');
MainDiv.style.width = "1000px;"
MainDiv.style.marginTop = "200px;"
document.getElementById('contentarea').appendChild(MainDiv);
}

“Contentarea”是一个已经存在的 div。我想添加多个“MainDiv”。我的代码在document.ready中执行

我得到这个“只允许一个根元素”的错误。

有什么线索吗?

这是我的html

        <div class="container-fluid" id="contentarea">
<div style="width:1000px;">
<div id="chart5" style="float:left !important; margin-top:10px;"></div>
<div id="chart10" style="float:left !important; margin-top:10px; margin-left:20px;"></div>
<div id="chart15" style="float:left !important; margin-top:10px; margin-left:20px;"></div>
<div id="chart16" style="float:left !important; margin-top:10px; margin-left:20px;"></div>
</div>
<div style="width:1000px; margin-top:200px;">
<div id="chartUitval5" style="float:left !important; margin-top:10px;"></div>
<div id="chartUitval10" style="float:left !important; margin-top:10px; margin-left:20px;"></div>
<div id="chartUitval15" style="float:left !important; margin-top:10px; margin-left:20px;"></div>
<div id="chartUitval16" style="float:left !important; margin-top:10px; margin-left:20px;"></div>
</div>
</div>

最佳答案

这是程序,非常简单:

function AddDivs(x) {
var MainDiv = document.createElement('div');
MainDiv.style.width = "1000px;";
MainDiv.style.marginTop = "200px;";
MainDiv.innerHTML = "Hello my id is " + x;
var id = "injectedDiv" + x;
MainDiv.setAttribute("id" , id);
document.getElementById('contentarea').appendChild(MainDiv);
}

$(document).ready(function() {

for (var x = 0;x < 10;x++) {
AddDivs(x);
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contentarea" style="-webkit-box-shadow: 0px 2px 31px 29px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 2px 31px 29px rgba(0,0,0,0.75);
box-shadow: 0px 2px 31px 29px rgba(0,0,0,0.75);" ></div>

关于javascript - only one root element is allowed 动态创建div时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50624104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com