如何计算javascript中p标签中的单词?

时间:2015-01-30 19:20:27

标签: javascript html

我想用javascript计算几段中的单词。我如何调用我的javascript函数?

<html>
    <head></head>

    <script type="text/javascript">
        function cnt() {
            var paragraphs = document.getElementsByTagName("p");

            for(var i = 0; i < paragraphs.length; i++) {
                alert(paragraphs[i].innerHTML);
            }
        }
    </script>

    <body>
        <p>some text</p>
        <p>some text</p>
        <p>text text text</p>
</html>

2 个答案:

答案 0 :(得分:2)

按间距拆分,并使用生成的数组length

function wordCount(elements) {
    var count = 0;
    for (var i = 0; i < elements.length; i++) {
        count += elements[i].textContent.split(/\s/).length;
    }
    return count;
}
var wordsInParagraphs = wordCount(document.getElementsByTagName("p"));

答案 1 :(得分:1)

您可以尝试这样的事情:

function cnt(){
    var paragraphs = document.getElementsByTagName("p");
    var count = 0;
    for(var i = 0; i < paragraphs.length; i++)
    {
        count += paragraphs[i].innerHTML.split(' ').length;
    }
}

请尝试以下代码段:

// I changed the name of function, in order to be more meaningfull.
function countWords(){
  
    // Select all the p elements in the page.
    var paragraphs = document.getElementsByTagName("p");
  
    // The counter.
    var count = 0;
  
    for(var i = 0; i < paragraphs.length; i++)
    {
        // Split the innerHtml of the current paragraph to count the words.
        count += paragraphs[i].innerHTML.split(' ').length;
    }
   
    document.write("Number of words: "+count);
}

countWords();
<p>some text</p>
<p>some text</p>
<p>text text text</p>