作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试测试一个 DOM 元素是否存在,如果存在则删除它,如果不存在则创建它。
var duskdawnkey = localStorage["duskdawnkey"];
var iframe = document.createElement("iframe");
var whereto = document.getElementById("debug");
var frameid = document.getElementById("injected_frame");
iframe.setAttribute("id", "injected_frame");
iframe.setAttribute("src", 'http://google.com');
iframe.setAttribute("width", "100%");
iframe.setAttribute("height", "400");
if (frameid) // check and see if iframe is already on page
{ //yes? Remove iframe
iframe.removeChild(frameid.childNodes[0]);
} else // no? Inject iframe
{
whereto.appendChild(iframe);
// add the newly created element and it's content into the DOM
my_div = document.getElementById("debug");
document.body.insertBefore(iframe, my_div);
}
检查它是否存在有效,创建元素有效,但删除元素无效。基本上,这些代码所做的就是通过单击按钮将 iframe 注入(inject)网页。我想要发生的是如果 iframe 已经在那里删除它。但由于某种原因,我失败了。
最佳答案
removeChild
应该在父级上调用,即:
parent.removeChild(child);
在您的示例中,您应该执行以下操作:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
关于JavaScript DOM 移除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830839/
我正在做一个项目,我的 android 在这个项目中作为一个网络服务器工作;输入带端口号的 IP 地址,打开 Web 界面,用户可以将文件上传到手机。我想在 Web 界面上显示一些图片,以便我们的界面
我是一名优秀的程序员,十分优秀!