簡體   English   中英

如何使用javascript刪除在內存中創建的元素

[英]how to delete an element that created in memory by using javascript

這是我的情況

順便說一下,我不想像波紋管代碼那樣將 vdom 插入到主體 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);
}

如屏幕截圖所示

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM