我想要一个javascript代码,计算当前文档中“Apple”文本出现的次数(让这个数字为N) 并创建一个新的div,它将上述文本添加N次。
到目前为止,我已经设法使用上面的示例计算“Apple”出现在文档中的次数 互联网,像这样:
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>
谢谢。
答案 0 :(得分:0)
试试这个
<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;
}