jQuery循环通过Child divs

时间:2012-07-23 19:55:59

标签: javascript jquery loops html each

<div id="ChosenCategory" class="chosen">
   <div class="cat_ch" name="1">
   <div class="cat_ch" name="2">
   <div class="cat_ch" name="3">
   <div class="cat_ch" name="5">
   <div class="clear"> </div>
</div>

我想循环遍历div.cat_ch如何?

这个失败了:

    $("div").each(function () {
       alert("FW");
       alert($(this).attr("name").val());
    });

8 个答案:

答案 0 :(得分:12)

$('#ChosenCategory').children('.cat_ch').each(function() {

});

或者

$('#ChosenCategory > .cat_ch').each(function() {

});

JQuery的.children方法和css3子选择器>将仅返回与选择器匹配的直接子项,示例中为类.cat_ch

如果要更深入地搜索DOM树,即包含嵌套元素,请使用.find或省略子选择器:

$('#ChosenCategory').find('.cat_ch').each( function(){} )

或者

$('#ChosenCategory .cat_ch').each( function(){} )

答案 1 :(得分:5)

$(function(){

    var items=$(".cat_ch")
     $.each(items,function (index,item) {

       alert($(item).attr("name"));
    });

});

工作样本:http://jsfiddle.net/GzKHA/

答案 2 :(得分:4)

如果您只想定位内部的Div,请尝试

$('#ChosenCategory div').each( function() {...} );

其他答案需要特定的类和/或也会处理父div中的非div。

答案 3 :(得分:3)

http://jsfiddle.net/2TRxh/

我认为你的问题在于获得属性$(this).attr("name").val()后尝试从div中获取val。在div上使用.val()没有意义。如果删除$(this).attr("name"),则会从div返回name属性。您可以通过在每个而不是div中使用类选择器来进一步指定要循环的div。 $(".cat_ch").each(function () {});此问题的其他各种答案都显示了这一点。

答案 4 :(得分:2)

    function loopOver(obj)
    {
        var chl=obj.firstChild;
        while(chl)
        {
            if(chl.nodeType==1)
            {
                var isAttr=chl.getAttribute('name');
                if(isAttr)
                {
                    alert(isAttr);
                }
            }
            chl=chl.nextSibling;
        }
    }

    //This is by far the fastest in terms of execution speed!!!
    var obj=document.getElementById("ChosenCategory");
    loopOver(obj);
    
Make sure to enclose the each `<div>` tag at the end of each!!

答案 5 :(得分:1)

$(".cat_ch").each(function () {
       alert("FW");
       alert($(this).attr("name").val());
    });

答案 6 :(得分:1)

如果要遍历div.cat_ch,则应将其用于jQuery选择器:

$("div.cat_ch").each(function () {
   alert("FW");
   alert($(this).attr("name").val());
});

您还可以使用jQuery children()方法遍历子元素:

$("#ChosenCategory").children().each(function () {
   alert("FW");
   alert($(this).attr("name").val());
});

循环遍历所需元素的第三种方式如下:

$("#ChosenCategory > div").each(function () {
   alert("FW");
   alert($(this).attr("name").val());
});

使用您想要的任何方式,没有最好的方法。

答案 7 :(得分:1)

$('.cat_ch').each(function(i, e) {
    alert('FW');
    alert(e.attr('name').val());
});
相关问题