jQuery 从子元素迭代内部子元素

jquery iterate over inner-child element from child elements

本文关键字:元素 内部 迭代 jQuery      更新时间:2023-09-26

我有下一个html:

<div id="segmenter">
    <div id="variable" name="Zone">
        <h3>Zona</h3>
        <ul>
            <li><input id="category" type="checkbox" value="Center">Center</li>
            <li><input id="category" type="checkbox" value="East">East</li>
            <li><input id="category" type="checkbox" value="South">South</li>
        </ul>
    </div>
    <div id="variable" name="Type of">
        <h3>Tipo de Restaurante</h3>
        <ul>
            <li><input id="category" type="checkbox" value="Freestander">Freestander</li>
            <li><input id="category" type="checkbox" value="Instore">Instore</li>
            <li><input id="category" type="checkbox" value="Mall">Mall</li>
        </ul>
    </div>
</div>

我想首先迭代具有 id"变量"的分段器的所有div 子项,然后遍历每个子"变量"的 id 为"类别"的所有输入。

使用 Chrome 开发者工具:

跟:

$("#segmenter > #variable")

我得到每个div 变量:[<div id=​"variable" name=​"Zona">​…​</div>​, <div id=​"variable" name=​"Tipo de Restaurante">​…​</div>​]

现在从这里开始,我尝试的所有内容都不起作用,例如:

$("#segmenter > #variable").find("#category");

我只得到 4 个输入"类别":[<input id=​"category" type=​"checkbox" value=​"Centro">​, <input id=​"category" type=​"checkbox" value=​"Freestander">​, <input id=​"category" type=​"checkbox" value=​"Instore">​, <input id=​"category" type=​"checkbox" value=​"Mall">​]

我不知道为什么,我需要的是迭代类似的东西:

var oVariables = $("#segmenter > #variable");
$.each(oVariables, function(){
    var oCategory = $(this).find("#category").text();//in the first call for div-name="zone", only have the first input-value"center"
    //Iterate Again
        //get checked values, etc
});

非常感谢。

ID 应始终是唯一的

在您的情况下使用类而不是 ID。 比如:

<div id="variable" name="Zone">
    _^_ here
<div class="variable" name="Zone"> //do this for all ids

和您的选择器

$("#segmenter > .variable").find(".category");

id 是唯一的。请改用类来存储集合。将所有 ID 更改为类,然后按如下所示进行迭代:

$.each($('div.variable'), function(elem){
    $.each($(elem).find('input.category'), function(childElem){
        //Do something with childElem here
    })
});

不要使用 ID 的!!Id 是独一无二的!!尝试改用类

我有同样的问题。我需要访问新的子标记。

我的方式:

var list_group_items = $("a.list-group-item");
    $.each(list_group_items,function(index,value){
        $(list_group_items[index]).hover(function(){
            $.each($(list_group_items[index]).find('small'), function(childElem,Element){
                console.log(Element);
                TweenLite.to(Element, 2, {"visibility":"visible"});
            });
        },function(){
            $.each($(list_group_items[index]).find('small'), function(childElem,Element){
                //Do something with childElem here
                TweenLite.to(Element, 2, {"visibility":""});
            });
        });
    });

注意1:$.each函数有两个参数,第一个是迭代索引,第二个是元素

注2:I使用TeenMax库进行动画。