简体   繁体   English

复制一个div的内部html并使用javascript将其粘贴到另一个div中

[英]copy inner html of a div and paste it in an other div with javascript

I have this element:我有这个元素:

<div id="divOne">
<button class="close-menu">close</button>
<ul>
    <li>hello</li>
</ul>
</div>

I want to copy inner html of #divOne and paste it to other div when page is loading.我想在页面加载时复制#divOne 的内部 html 并将其粘贴到其他 div。

I do with this code but my button does not work anymore.我使用此代码,但我的按钮不再起作用。

document.getElementById('divTwo').innerHTML = document.getElementById("divOne").innerHTML;

Thank you谢谢

You need to delegate the click handler, something like您需要委托点击处理程序,例如

 // handle clicks on all document buttons $(document).on('click', 'button', buttonClick); // copy #divOne html to #divTwo $('#divTwo').html($('#divOne').html()); // click handler demo function buttonClick(e) { var result = $('#result'); var id = $(this.parentNode).attr('id'); result.html('clicked button within: #' + id); // comment @cssGeek demo $('div').css('color', '#000'); $('#'+id).css('color', 'red'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="divOne"> <button class="close-menu">close</button> <ul> <li>hello</li> </ul> </div> <div id="divTwo"></div> <div id="result"></div>

my button does not work anymore.我的按钮不再起作用了。

Well in this case you have to delegate the event to the closest static parent or to the document :那么在这种情况下,您必须将事件委托给最近的静态父级或document

I guess you are using jquery:我猜你正在使用 jquery:

$(document).on('click', '.close-menu', function(e){
    console.log('clicked.');
});

I want to copy inner html of #divOne and paste it to other div when page is loading.我想在页面加载时复制#divOne 的内部 html 并将其粘贴到其他 div。

What you have posted is doing it other way round instead you have to do this:您发布的内容是以其他方式进行的,而您必须这样做:

document.getElementById('divTow').innerHTML = document.getElementById("divOne").innerHTML;

try this尝试这个

 document.getElementById('divTwo').innerHTML = document.getElementById("divOne").innerHTML;
 <div id="divOne"> <button class="close-menu">close</button> <ul> <li>hello</li> </ul> </div> <div id="divTwo"></div>

For those who still see this post:对于那些仍然看到这篇文章的人:

If you want the buttons (onClick event,...) work after adding new HTML to an element, use the code below:如果您希望按钮(onClick 事件,...)在向元素添加新 HTML 后工作,请使用以下代码:

element.insertAdjacentHTML(position, text);

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

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

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