繁体   English   中英

无法将已经存在的 h1 附加到另一个 div

[英]Unable to append an already-existing h1 to another div

单击按钮后,我正在尝试将h1元素(已在 HTML 中)附加到 div。 这应该很容易,但对于我的生活,我无法弄清楚为什么这不起作用。

 $('button').on('click', function() { $('div').append($('h1')); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button type="button"></button> <h1>lorem ipsum</h1> <div></div>

我知道我可以直接向 DOM 添加一个新的h1 ,但是我试图将已经存在的h1添加到 HTML 中,因为它在实际项目中非常动态。

任何想法为什么它不起作用?

你应该尝试克隆它

$('div').append( $('h1:first').clone() ); 

 $('button').on('click', function(){ //get h1 content with parent container var htmlCont = $('h1').wrap('<p/>').parent().html(); $('h1').parent().remove(); /* //get h1 content and append it var htmlCont = $('h1').html(); $('h1').remove(); */ $('div').append(htmlCont); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button type="button">tes</button> <h1>lorem ipsum</h1> <div></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM