4

このようなマークアップがあるとしましょう

<html id="test">
<body>
Some text node.
<div class="cool"><span class="try">This is another text node.</span></div>
Yet another test node.
</body>
</html>

私のjsコード

function countText(node){
 var counter = 0;
 if(node.nodeType === 3){
     counter+=node.nodeValue.length;
     countText(node);
 }
 else{}
}

テキストノードを数えたい場合

console.log("count text : " + countText(document.getElementById("test"));

これは私にカウントを返すはずですが、機能していません。さらに、他の条件に何を入れるべきですか。nodeType を使用したことがないので、使用に問題があります。どんな助けでも大歓迎です。

4

2 に答える 2

7

あなたのコードにはいくつかの間違いがあります:

  • HTML の形式が正しくありません。
  • counterテキストを増やすのではなく、テキストを追加しています。
  • ノードの子をループすることはありません。常に同じノードを再帰呼び出しに渡します。
  • ノードがテキスト ノードでない場合は何もしません。

これはうまくいきます:

function countText(node){
    var counter = 0;
    if(node.nodeType === 3){
        counter++;
    }
    else if(node.nodeType === 1) { // if it is an element node, 
       var children = node.childNodes;    // examine the children
       for(var i = children.length; i--; ) {
          counter += countText(children[i]);
       }
    }
    return counter;  
}

alert(countText(document.body));

デモ

どの番号がどのノード タイプに対応するかは、こちらで確認できます


アップデート:

単語を数えたい場合は、まず各テキスト ノードを単語に分割する必要があります。以下では、単語が空白で区切られていると仮定します。

if(node.nodeType === 3){
    counter = node.nodeValue.split(/\s+/g).length;
}

更新 2

再帰関数を使用したいのはわかっていますが、単語だけを数えたい場合は、もっと簡単で効率的な方法があります。

function countWords(node){
    // gets the text of the node and all its descendants
    var text = node.innerText || node.textContent
    return text.split(/\s+/g).length;
}
于 2011-04-14T00:22:33.070 に答える
1

あなたは次のようなものが欲しい

function countTextNodes(node) {
    var n = 0;
    if(node.nodeType == 3)
        n = 1;
    for(var i = 0; i < node.childNodes.length; ++i)
        n += countTextNodes(node.childNodes[i]);
    return n;
}

これはよりコンパクトなコードに圧縮できますが、ここでは読みやすさを優先しました。

テキスト ノードをカウントするルートでこれを呼び出します。たとえば、ドキュメント全体のテキスト ノードをカウントするには、 を呼び出しますcountTextNodes(document.getDocumentElement())

于 2011-04-14T00:14:09.590 に答える