0

因此,假设我有一个非常基本的页面,其中包含一个正文、一个 div 和一个带有一些文本的段落元素。

<body>
  <div>
    <p>some text</p>
  <div>
</body>

根据浏览器的不同,body/div 元素会有文本节点(nodeType === 3, nodeValue === "--blank--")。但是,P 元素将具有合法的文本节点,其 nodeValue === "some text"。

我想知道的是代表空白等于的“假”文本节点的“nodeValue”(--blank--)是什么,因为我想编写一个 if 测试,让我过滤掉假文本节点.

例子:

var body = document.getElementsByTagName("body")[0];  // shortcut to body element.
console.log(body.childNodes[0].nodeValue) // maps to one of the fake text nodes that are blank.
// returns a blank line. What is that "blank" equal to? It's not 'null' or "" or undefined...

干杯,亚历克斯

4

2 回答 2

2

您可以使用正则表达式,例如:

var re = /\S/; // Match non-whitespace
if (node.nodeType == 3 && re.test(node.nodeValue)) {
  // text node has something other than whitespace
}

请注意,浏览器认为空格和匹配的内容略有\s不同,但这在这里可能并不重要。

于 2011-10-05T02:26:26.027 回答
2

只需trim()[docs] 空格,看看是否还有任何剩余:

if( body.childNodes[0].nodeValue.trim() ) {
    // more than white space
} else {
    // just white space
}

如果只有空格,您最终会得到一个虚假的值。否则,它将是真实的。

文档链接提供以下兼容性填充程序:

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    };
}
于 2011-10-05T01:31:09.847 回答