简体   繁体   English

如何清理divs内容?

[英]How to clean up divs contents?

I heared that simply to say document.getElementById('divId').innerHTML = ""; 我听到的只是说document.getElementById('divId').innerHTML = ""; is not safe for future divId contents editing via JS so how to clean up divs contents safely? 通过JS编辑将来的divId内容并不安全,那么如何安全清理divs内容?

What should always work is: 始终应该起作用的是:

var div = document.getElementById('divId');
while(div.hasChildNodes()) {
    div.removeChild(div.firstChild);
}

innerHTML is not part of any specification but is widely supported by browsers. innerHTML不是任何规范的一部分,但已被浏览器广泛支持。

I wrote something similar to Felix Kling, only diffirence is that I wanted to pass the id or the reference. 我写了一些与Felix Kling类似的东西,唯一的区别是我想传递id或引用。 So I wrote it like this: 所以我这样写:

function removeAllChildNodes(node) {
    i = (typeof(node) == "object") ? node : document.getElementById(node);

    while (i.hasChildNodes()) {
        i.removeChild(i.firstChild);
    }
}

Setting the innerHTML attribute to nothing will eliminate any DOM nodes withing the specified DIV. 将innerHTML属性设置为nothing将消除具有指定DIV的任何DOM节点。 There is no risk of "safety". 没有“安全”的风险。

You can do this safely :P 你可以安全地做到这一点:P

I believe this is where JS frameworks, such as jQuery, come to light... they are optimized for cross-browser security - which includes secure DOM element removal, although you will loose a bit of computing speed (setting innerHTML is always the fastest way) 我相信这是JS框架(例如jQuery)的亮点……它们针对跨浏览器安全性进行了优化-包括安全的DOM元素删除,尽管您会降低一些计算速度(设置innerHTML始终是最快的)方式)

as for others wondering about security of this, some browsers (notably MSIE) have flaws that would crash the browser or allow malicious procedures to be executed on client's side under certain conditions, so that's why setting innerHTML might not be as secure as people use to think ;-) 至于其他对此感到疑惑的人,某些浏览器(尤其是MSIE)存在一些缺陷,这些缺陷会导致浏览器崩溃或在某些条件下允许在客户端执行恶意程序,因此这就是为什么设置innerHTML可能不如人们习惯的那样安全。认为;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM