0

ですから、body、単一の 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 に答える