1

这里有点奇怪的故障。

当 IF 语句被注释掉时, a 的标签名称childNode被正确记录,但是一旦你取消 IF 语句的注释,那么childNodes 标签名称就会被记录为“ #TEXT”。

<body>
    <div id="page_Wrapper">
        <h1>h1</h1>
        <br />
        <br />
        <br />
        <b>b</b>
        <br />
        <i>i</i>
        <br />
        <u>u</u>
        <div>div</div>
        <span>span</span>
    </div>

    <script>
        window.onLoad = removeTags();

        function removeTags(){
            var allTags = document.getElementById("page_Wrapper").childNodes;
            console.log("allTags length: " + allTags.length);

            for (var i = 0; i < allTags.length; i++){
                var tag = allTags[i].nodeName.toLowerCase();
                console.log(tag);
            /*
                if (tag != "b" || tag != "br" || tag != "i"){
                    allTags[i].parentNode.removeChild(allTags[i]);
                }
            */
            }
        }
    </script>
</body>

http://jsfiddle.net/MythOfEchelon/VpNWA/3/

完成,工作代码:

<body>
    <div id="page_Wrapper">
        <h1>h1</h1>
        <br />
        <br />
        <br />
        <b>b</b>
        <br />
        <i>i</i>
        <br />
        <u>u</u>
        <div>div</div>
        <span>span</span>
    </div>

    <script>
        window.onload = removeTags;

        function removeTags(){
            var allTags = document.getElementById("page_Wrapper").childNodes;
            var i = allTags.length;

            while (i--){
                var tag = allTags[i].nodeName.toLowerCase();
                console.log(tag);

                if (tag != "b" && tag != "br" && tag != "i"){
                    allTags[i].parentNode.removeChild(allTags[i]);
                }
            }
        }
    </script>
</body>
4

2 回答 2

1

请参阅条件(tag != "b" || tag != "br" || tag != "i")选择任何节点(它可能应该是(tag != "b" && tag != "br" && tag != "i") instead).因此在每个循环上调用 removeChild 函数。

如果allTags[i].parentNode.removeChild(allTags[i]);被替换为

var x = allTags[i];
x.parentNode.removeChild(x);

行为不同。另请参阅:removechild loop exits before finish

于 2012-07-03T13:43:20.030 回答
0

您可以添加此行以检查它是否是文本节点

for (...) {
    if (allTags[i].nodeType == 3) continue; //nodeType = 3 means it is a text node
    ...
}
于 2012-07-03T13:15:21.883 回答