[英]put content of div1 into div2 onclick event
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 我一直在想,应该使用jquery来用div1 onclick的内容填充div2的最佳方法是
<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. 就像Andy的回答那样 ,与其求助于序列化为HTML然后再将其应用于其他元素,不如克隆节点更好。
$('#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. 由于我使用过
e.preventDefault()
,您也可能会丢失代码的javascript:void
,因为该链接的默认操作已被阻止。
See the jQuery API: 请参阅jQuery API:
$('#div2').html($('#div1').html());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.