原生 Vanilla javascript 有好的方法clone element帶有event? 謝謝
舉例子如下:
<div class="soruce">
<h1>我有click event</h1>
<h2>我有click event</h2>
</div>
<div class="dest"></div>
script
// clone elememts with event,cloneNode()無法實現
window.onload = function () {
let h1_event=document.querySelector("h1");
let h2_event=document.querySelector("h2");
//addEventListener()
h1_event.addEventListener('click', function (event) {
console.log(event.currentTarget);
});
h2_event.addEventListener('click', function (event) {
console.log(event.currentTarget);
});
// clone elememts with event
const sourceElements = document.querySelector(".source").children;
const sourceElementsArray = Array.from(sourceElements);
sourceElementsArray.forEach((element) => {
const clonedElement = element.cloneNode(true);
document.querySelector(".dest").appendChild(clonedElement);
});
maybe this method?
MDN CloneNode
Sorry ...saw your code ,
maybe someone else can help...
just ignore my answer
cloneNode() 函式不會複製 Event Listener,所以只能在複製完後補上事件要觸發的函式。
然後你class的名稱好像打錯了,html是soruce,js則是source。
<div class="source">
<h1>我有click event</h1>
<h2>我有click event</h2>
</div>
<div class="dest"></div>
<script>
let h1_event=document.querySelector("h1");
let h2_event=document.querySelector("h2");
h1_event.addEventListener('click', function (event) {
console.log(event.currentTarget);
});
h2_event.addEventListener('click', function (event) {
console.log(event.currentTarget);
});
const sourceElements = document.querySelector(".source").children;
console.log(sourceElements);
for(let element of sourceElements)
{
const clonedElement = element.cloneNode(true);
clonedElement.addEventListener('click',function (event) {
console.log(event.currentTarget);
});
document.querySelector(".dest").appendChild(clonedElement);
}
</script>
reference: StackOverflow Discuss