121 javascript
我试图<div>动态创建一个附加<div>内部.到目前为止我有这个工作:
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
Run Code Online (Sandbox Code Playgroud)
我只是在创建并将第二个div附加到第一个div时遇到了麻烦.
我基本上想做这个作为最终标记:
<div id="block" class="block">
<div class="block-2"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
Mic*_*ski 219
使用相同的过程.您已经拥有了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);
Run Code Online (Sandbox Code Playgroud)
事件创建的顺序不必像我上面那样.innerDiv在将两者都添加到外部div之前,您可以交替地将新附加到外部div <body>.
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);
Run Code Online (Sandbox Code Playgroud)
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
var div2 = document.createElement('div');
div2.className = 'block-2';
iDiv.appendChild(div2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
397932 次 |
| 最近记录: |