2

コンテナのdiv.exampleには、さまざまな第1レベルの子要素(sectiondivulnav、...)を含めることができます。これらの要素の量と種類はさまざまです。

最も発生する直接の子のタイプ(たとえば、 div )を見つける必要があります。単純なjQueryまたはJavaScriptソリューションとは何ですか?

jQuery 1.7.1が利用可能ですが、IE <9(array.filter)でも機能するはずです。

編集:@ Jasper、@ Vega、@RobinMabenに感謝します:)

4

3 に答える 3

3

を使用して子を繰り返し処理し、見つけたs.children()の数をログに記録します。element.tagName

//create object to store data
var tags = {};

//iterate through the children
$.each($('#parent').children(), function () {

    //get the type of tag we are looking-at
    var name = this.tagName.toLowerCase();

    //if we haven't logged this type of tag yet, initialize it in the `tags` object
    if (typeof tags[name] == 'undefined') {
        tags[name] = 0;
    }

    //and increment the count for this tag
    tags[name]++;
});

これで、オブジェクトは、要素tagsの子として発生した各タイプのタグの番号を保持します。#parent

デモは次のとおりです。http://jsfiddle.net/ZRjtp/(コンソールでオブジェクトを監視します)

次に、最も多く発生したタグを見つけるには、次のようにします。

var most_used = {
        count : 0,
        tag   : ''
    };

$.each(tags, function (key, val) {
    if (val > most_used.count) {
        most_used.count = val;
        most_used.tag   = key;
    }
});

オブジェクトは、最も使用されたタグとそのmost_used使用回数を保持するようになりました。

これがデモです:http://jsfiddle.net/ZRjtp/1/

于 2012-04-17T19:40:19.937 に答える
2

編集:以下のようなjQuery関数の方が便利だと思います。

デモ

$.fn.theMostChild = function() {
    var childs = {};
    $(this).children().each(function() {
        if (childs.hasOwnProperty(this.nodeName)) {
            childs[this.nodeName] += 1;
        } else {
            childs[this.nodeName] = 1;
        }
    });
    var maxNode = '', maxNodeCount = 0;
    for (nodeName in childs) {
        if (childs[nodeName] > maxNodeCount) {
            maxNode = nodeName;
            maxNodeCount = childs[nodeName];
        }
    }
    return $(maxNode);
}

そして、あなたはできる、

$('div.example').theMostChild().css('color', 'red');

以下のような関数は、子要素の数を提供し、そこから最大数を取得できます。以下を参照、 デモ

$(function () {
    var childs = {};
    $('div.example').children().each(function () {
        if (childs.hasOwnProperty(this.nodeName)) {
            childs[this.nodeName] += 1;
        } else {
            childs[this.nodeName] = 1;
        }
    });

    for (i in childs) {
        console.log(i + ': ' + childs[i]);
    }
});
于 2012-04-17T19:43:16.963 に答える
1

これは、予想される子ノードのタイプに関する情報がないと不可能です。

編集ジャスパーが指摘したように、事前にタグ名を知る必要はない可能性があります。以下は、特定のセレクターのセット内のみを検索している場合に機能します。

var selectorArray = ['div', 'span', 'p',........]

var matches = $(div).children(selectorArray.join());    
var max = 0, result = [];    
$.each(selectorArray, function(i, selector){

    var l = matches.filter(selector).length;
    if(l > max){
     max = l;
     result[max] = selector;
    }

});

result[max]タグ名とmax発生回数を示します

于 2012-04-17T19:46:51.217 に答える