javascript - 如何使用javascript删除在内存中创建的元素
问题描述
这是我的情况
顺便说一句,我不想像下面显示的代码那样将 vdom 插入到 body DOM 中。
// vdom
const alink = document.createElement('a');
document.body.appendChild(alink);
alink.click();
document.body.removeChild(alink);
const virtualDomConvert = (filename = ``) => {
const svg = document.querySelector(`[id="live_map_svg"]`);
const clone = svg.cloneNode(true);
clone.id = 'vdom_svg';
// autoRemoveAttributes(clone);
const html = clone.outerHTML;
// add xml namespace, support browser open preview
const xml = `
<?xml version="1.0" encoding="UTF-8"?>
${html}
`.trim();
const alink = document.createElement('a');
alink.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml));
alink.setAttribute('download', filename);
alink.style.display = 'none';
const vdom = document.createElement(`div`);
vdom.appendChild(alink);
alink.click();
vdom.removeChild(alink);
// ❓ how to delete vdom ???
// vdom.remove();
// vdom.parentElement.removeChild(vdom);
}
我尝试了一些方法,但仍然无法正常工作。
参考
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
解决方案
解决方案
我指出这
vdom
只是在 JS 环境中,而不是在真正的 DOM 上下文中,因此删除vdom
.
const log = console.log;
const virtualDomConvert = (filename = ``) => {
const svg = document.querySelector(`[id="live_map_svg"]`);
const clone = svg.cloneNode(true);
clone.id = 'vdom_svg';
// autoRemoveAttributes(clone);
const html = clone.outerHTML;
// add xml namespace, support browser open preview
const xml = `
<?xml version="1.0" encoding="UTF-8"?>
${html}
`.trim();
const alink = document.createElement('a');
alink.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml));
alink.setAttribute('download', filename);
alink.style.display = 'none';
const vdom = document.createElement(`div`);
vdom.appendChild(alink);
alink.click();
vdom.removeChild(alink);
log(`vdom`, vdom);
setTimeout(() => {
delete this.vdom;
log(`deleted vdom`, vdom);
}, 3000);
}
如屏幕截图所示
推荐阅读
- docker - 通过特定接口将所有传入和传出流量路由到/从 Docker 容器
- neural-network - CNN 使用一层过拟合
- android - 如何从房间数据库中检索单个对象?
- r - 如何在 R 代码中使用 sas 宏变量
- node.js - 如何使用 node.js 更新 firestore 中的嵌套字段?
- python - 迭代模型火车时,纪元突然结束
- amazon-web-services - Cloudformation 删除删除 S3 存储桶,尽管有 DeletionPolicy: Retain
- php - 如何为 AJAX 发送纬度和经度值以从 GeoNames 获取信息
- amazon-web-services - 如何:terraform 雪花阶段凭证并使用 AWS IAM 角色 arn
- python - python中替换函数的问题(替换相同的字符串)