如何删除DOM元素上JS自定义赋值属性并保留原生默认属性
技术实现方案
方案1:全量自定义属性识别与清理(通用场景)
核心思路是通过创建同类型空原生DOM元素,得到原生属性白名单,对比筛选出自定义属性:
// 1. 获取元素所有自定义属性集合 function getCustomDOMProperties(el) { // 创建同标签名的空元素,作为原生属性白名单参照 const emptyEl = document.createElement(el.tagName.toLowerCase()); const nativeProps = new Set(Object.keys(emptyEl)); const customProps = {}; // 遍历当前元素的自有可枚举属性 for (const key in el) { if (el.hasOwnProperty(key) && !nativeProps.has(key)) { customProps[key] = el[key]; } } return customProps; } // 2. 删除所有自定义属性,仅保留原生属性 function clearCustomDOMProperties(el) { const emptyEl = document.createElement(el.tagName.toLowerCase()); const nativeProps = new Set(Object.keys(emptyEl)); for (const key in el) { if (el.hasOwnProperty(key) && !nativeProps.has(key)) { delete el[key]; } } }
调用示例:
const customProps = getCustomDOMProperties(el); console.log(customProps); // 输出 {a:1, b:[], c: C实例} clearCustomDOMProperties(el); console.log(el.a); // 输出 undefined
方案2:针对性清理jsPlumb缓存(适配你的业务场景)
你当前的问题核心是jsPlumb遗留的_jsPlumbConnections缓存属性,不需要全量清理自定义属性,直接针对性删除即可,性能更高、风险更低,修改你的业务代码如下:
this.plumb.bind('click', function(conn){ connect.connections.splice(connect.connections.indexOf(conn.cn), 1); jsPlumb.deleteConnection(conn); // 新增:清理源元素和目标元素上的jsPlumb缓存属性 delete conn.cn.source._jsPlumbConnections; delete conn.cn.target._jsPlumbConnections; attr_element({id: null, class: null}, conn.cn.source.backup); attr_element({id: null, class: null}, conn.cn.target.backup); connect.render(); });
注意事项
- 全量清理自定义属性前请确认元素上没有其他业务侧挂载的自定义属性,避免业务逻辑异常
- 如果jsPlumb后续版本新增了其他缓存属性,可在针对性清理逻辑中补充对应属性的删除操作即可
内容的提问来源于stack exchange,提问作者Weilory
相关产品推荐
相关产品推荐

