iT邦幫忙

1

原生 Vanilla javascript 如何 clone element 帶有event ?

  • 分享至 

  • xImage

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

froce iT邦大師 1 級 ‧ 2024-12-07 14:17:00 檢舉
沒辦法,原生的api你得不到event
一個建議是用事件委派,將事件綁定在父元素
https://www.freecodecamp.org/news/event-delegation-javascript/

另外一個可能可行方法是用下面這個:
https://www.npmjs.com/package/geteventlisteners

但我是建議乾脆去學個框架...基本上你不會遇到這種問題。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

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

我要發表回答

立即登入回答