Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript计算文档中字符串的外观?_Javascript_Count_Document - Fatal编程技术网

使用javascript计算文档中字符串的外观?

使用javascript计算文档中字符串的外观?,javascript,count,document,Javascript,Count,Document,我想要一个javascript代码来计算文本“Apple”在当前文档中出现的次数(让这个数字为N) 并创建一个新的div,在其中添加前面提到的文本N次 到目前为止,我已经通过在上找到的一个例子计算了“苹果”在文档中出现的次数 互联网,就像这样: JS window.getCount=函数(父函数,getChildrensChildren){ var-relevantChildren=0; var children=parent.childNodes.length; 对于(变量i=0;i

我想要一个javascript代码来计算文本“Apple”在当前文档中出现的次数(让这个数字为N) 并创建一个新的div,在其中添加前面提到的文本N次

到目前为止,我已经通过在上找到的一个例子计算了“苹果”在文档中出现的次数 互联网,就像这样:

JS
window.getCount=函数(父函数,getChildrensChildren){
var-relevantChildren=0;
var children=parent.childNodes.length;
对于(变量i=0;i
HTML

苹果
苹果。
苹果
苹果
苹果
苹果
谢谢。

试试这个


苹果
苹果。
苹果
苹果
苹果
苹果
window.getCount=函数(父函数,getChildrensChildren){
var-relevantChildren=0;
var children=parent.childNodes.length;
对于(变量i=0;i
那么您现在想要什么?我如何创建一个新的div,在其中添加“Apple”的次数与文档中找到的次数相同?是否有可能是重复的?是否有原因您无法手动创建div,因此它已经是DOM的一部分,然后稍后再填充?我已经更新了答案
window.getCount = function(parent, getChildrensChildren){
    var relevantChildren = 0;
    var children = parent.childNodes.length;
    for(var i=0; i < children; i++){
        if(parent.childNodes[i].nodeType != 3){
            if(getChildrensChildren)
                relevantChildren += getCount(parent.childNodes[i],true);
            relevantChildren++;
        }
    }
    return relevantChildren;
}
<pre>
<div id="test">
    <span>Apple</span>
    <span>Apple.</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
</div>
<pre>
<a href="#" onclick="alert(getCount(document.getElementById('test'), false));">Show counter:</a>
<pre>
<div id="test">
    <span>Apple</span>
    <span>Apple.</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
    <span>Apple</span>
</div>
<pre>
<a href="#" onclick="alert(getCount(document.getElementById('test'), false));">Show counter:</a>
<div class="response">

</div>


window.getCount = function(parent, getChildrensChildren){
        var relevantChildren = 0;
        var children = parent.childNodes.length;
        for(var i=0; i < children; i++){
            if(parent.childNodes[i].nodeType != 3){
                if(getChildrensChildren)
                    relevantChildren += getCount(parent.childNodes[i],true);
                relevantChildren++;
            }
        }
            document.body.getElementsByTagName('div')[1].innerHTML  = relevantChildren;
        return relevantChildren;
    }