如何统计子节点中出现最多的节点类型及其百分比?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function main_node_percent(){
var percent;
var tag_name;
//如何统计.father中最多出现的tagname (这里是div)出现在.father中次数的百分比?
......
$("#tag_name").html(tag_name);
$("#percent").html(percent);

</script>
<div class="father">
<div>I</div>
<p>love</p>
<span>you</span>
<div>forever</div>
<a href="#">hello</a>
<br>
<a href="#">world</a>
<div>boy</div>
</div><div>
<div>这里显示结果:</div>
出现最多:<span id="tag_name"></span>
出现概率:<span id="percent"></span>
</div>
<button onclick="main_node_percent()">统计</button>

解决方案 »

  1.   

    我能想到的也就是遍历一下。
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        function main_node_percent(){
            var percent;
            var tag_name;
            //如何统计.father中最多出现的tagname (这里是div)出现在.father中次数的百分比?
            var counts = {};
    var tags = [];
    var count = 0;
    $(".father *").each(function() {
    count++;
    if (counts[this.tagName])
    counts[this.tagName]++;
    else {
    counts[this.tagName] = 1;
    tags.push(this.tagName);
    }
    });
    tags.sort(function(a, b) {
    return counts[b] - counts[a];
    });

    tag_name = tags[0];
    percent = counts[tags[0]] / count * 100 + "%";

    $("#tag_name").html(tag_name);
            $("#percent").html(percent);
        } 
    </script>
    <div class="father">
        <div>I</div>
        <p>love</p>
        <span>you</span>
        <div>forever</div>
        <a href="#">hello</a>
        <br>
        <a href="#">world</a>
        <div>boy</div>
    </div><div>
        <div>这里显示结果:</div>
        出现最多:<span id="tag_name"></span>
        出现概率:<span id="percent"></span>
    </div>
    <button onclick="main_node_percent()">统计</button>