I have two divs as follows:
<div id='div1'>
<p>Hello world!</p>
</div>
<div id='div2'>
</div>
<a id='test' href='javascript:void()'>Click me to fill in div2</a>
I have been wondering what should be the best way to fill in div2 with the content of div1 onclick using jquery in order to have
<div id='div1'>
<p>Hello world!</p>
</div>
使用.contents()
.clone()
和.append()
将$("#div1")
的内容克隆到$("#div2")
.append()
:
$("#div2").append($("#div1").contents().clone());
Rather than resorting to serialising to HTML and then applying that to the other element, as Andy's answer does , it would be nicer to clone the nodes.
$('#test').click(function(e) {
e.preventDefault();
$('#div1').contents().clone(true).appendTo('#div2');
});
This has the advantage that any data or events on the elements cloned will continue to exist on the new elements. Since I've used e.preventDefault()
, you can also lose the javascript:void
bit of your code, because the link's default action has been prevented.
See the jQuery API:
$('#div2').html($('#div1').html());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.