克隆元素及其所有事件

编程入门 行业动态 更新时间:2024-10-25 20:30:05
本文介绍了克隆元素及其所有事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在页面中克隆了一个textarea,但是克隆元素没有任何主要元素的事件,有没有办法克隆克隆元素中的所有事件?

I'm cloning a textarea in a page but the cloned element doesn't have any event of the primary element, is there any way to clone all events in cloned element?

var dupNode = node.cloneNode(deep);

推荐答案

你可以使用 getEventListeners 在节点上?不知道支持是怎么回事,或者它是否只在控制台中支持?

You can maybe use getEventListeners on nodes? Don't know how the support is, or if it's only supported in the console?

function cloneMassive(node) { // Clone the node, don't clone the childNodes right now... var dupNode = node.cloneNode(false); var events = getEventListeners(node); for(var p in events) { // All events is in an array so iterate that array: events[p].forEach(function(ev) { // {listener: Function, useCapture: Boolean} dupNode.addEventListener(p, ev.listener, ev.useCapture); }); } // Also do the same to all childNodes and append them. if (node.childNodes.length) { [].slice.call(node.childNodes).forEach(function(node) { dupNode.appendChild(cloneMassive(node)); }); } return dupNode; }

var dupBody = cloneMassive(document.body);

但似乎 getEventListeners 不是真的支持:

使用addEventListener获取附加到节点的事件侦听器

如果需要复制所有事件属性节点,你需要一个所有的列表,然后简单地复制它们:

If you need to copy all event properties on the node as well you will need a list of all, and then simply copy them over:

['onclick', 'onmouseover', '...'].forEach(function(method) { dupNode[method] = node[method]; });

更多推荐

克隆元素及其所有事件

本文发布于:2023-11-24 05:24:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624107.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!