我想动态地将已经定义的“旧div”标签的内容附加到“new div”标签,但它不起作用。我试过的代码附在下面。 还有一个问题,如何动态删除附加的div标签?
<html>
<head>
<script type="text/javascript">
function add() {
var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.appendChild( i );
}
</script>
</head>
<body>
<div id="old">
Content of old div
</div>
<div id="new">
</div>
<button onclick="add()">Add</button>
</body>
</html>
答案 0 :(得分:4)
试试这个
var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.innerHTML += i.innerHTML;
答案 1 :(得分:3)
<html>
<head>
<script type="text/javascript">
function add() {
var i = document.getElementById( 'old' );
var d = document.createElement( 'div' );
d.id = "new1";
d.innerHTML = i.innerHTML ;
var p = document.getElementById('new');
p.appendChild(d);
}
function removeLocation() {
var d = document.getElementById( 'new1' );
var p = document.getElementById('new');
p.removeChild(d);
}
</script>
</head>
<body>
<div id="old">
Content of old div
</div>
<hr/>
<div id="new">
</div>
<hr/>
<button onclick="add();">Add</button><br>
<button onclick="removeLocation();">Remove</button>
</body>
</html>