JavaScript 在 Div 标签上动态附加另一个 Div 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8316940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:01:30  来源:igfitidea点击:

JavaScript Appending another Div data on Div Tag Dynamically

javascript

提问by Naeem Ul Wahhab

I want to append the content of an already defined "old div" tag to the "new div" tag dynamically but its not working. The code i tried is attached below. And one more question, how to remove that appended div tag dynamically?

我想动态地将已定义的“旧 div”标签的内容附加到“新 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>

回答by Ash Burlaczenko

Try this

试试这个

var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.innerHTML += i.innerHTML;

回答by Naeem Ul Wahhab

ok I solved it. There was some error in my code. Its working now.

好的,我解决了。我的代码中有一些错误。它现在工作。

    <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>