原生 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);
});

2 个回答

0

fuwu1245

iT邦见习生 ‧ 2024-12-07 10:15:55

maybe this method?
MDN CloneNode
Sorry ...saw your code ,
maybe someone else can help...
just ignore my answer

0

Cavey

iT邦新手 5 级 ‧ 2024-12-11 19:53:45

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