繁体   English   中英

文本节点的“ nodeValue”属性为空-然后如何测试呢?

[英]“nodeValue” property of text node is blank - how do I test for it then?

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

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

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

我想知道的是,一个“假”文本节点的“ nodeValue”(-空白–)代表空白,等于什么,因为我想编写一个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...

干杯,亚历克斯

the whitespace, and see if there's anything left: 只需trim() 空格,看看是否还有剩余:

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

如果只有空格,那么最终将得到一个false值。 否则,它将是真实的。

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

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

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

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

请注意,浏览器考虑的空白以及与\\s匹配的内容存在细微差异,但这在这里可能并不重要。

暂无
暂无

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

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