gpt4 book ai didi

javascript - 动态创建
和追加

转载 作者:IT王子 更新时间:2023-10-29 02:39:11 27 4
gpt4 key购买 nike

我正在尝试创建一个 <div>动态地,附加一个 <div>里面。到目前为止我有这个有效:

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

我只是在创建第二个 div 并将其附加到第一个 div 时遇到问题。

我基本上想将此作为最终标记:

<div id="block" class="block">
<div class="block-2"></div>
</div>

最佳答案

使用相同的过程。您已经有了变量 iDiv仍然引用原始元素 <div id='block'>你创造了。您只需要创建另一个 <div>并调用appendChild() .

// Your existing code unmodified...
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

http://jsfiddle.net/W4Sup/1/

事件创建的顺序不必像我上面那样。您也可以附加新的 innerDiv在将两者添加到 <body> 之前添加到外部 div .

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';

// Create the inner div before appending to the body
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

// Then append the whole thing onto the body
document.getElementsByTagName('body')[0].appendChild(iDiv);

关于javascript - 动态创建 <div> 和追加 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14004117/

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