You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery的.each函数正确解析父元素及对应子元素?

jQuery嵌套遍历的范围问题解析

需求与问题场景

目标是构建关联数组,存储.image类中的编号和对应.qty输入框的值,使用jQuery的.each()遍历实现,但实际遍历结果不符合预期。

原始HTML与JS代码

<div class="image 324">
    <div class="options">
        <p>Sizes</p>
        <p><input type="text" name="qty1" class="qty" value=""> 8x10</p>
        <p><input type="text" name="qty2" class="qty" value="1">11x14</p>
        <p><input type="text" name="qty3" class="qty" value="">16x20</p>
    </div>
</div>
<div class="image 231">
    <div class="options">
        <p>Sizes</p>
        <p><input type="text" name="qty4" class="qty" value="2"> 8x10</p>
        <p><input type="text" name="qty5" class="qty" value="">11x14</p>
        <p><input type="text" name="qty6" class="qty" value="1">16x20</p>
    </div>
</div>

<script>
$(function() {
 $('.image').each(function(index) {
    console.log( index+": "+$(this).attr('class') );
    $('.qty').each(function(index) {
      console.log( index+': '+$(this).val() );
    });
  });
});
</script>

预期输出

0: image 324
0: 
1: 1
2:
1: image 231
0: 2
1:
2: 1

实际输出

0: image 324
0: 
1: 1
2: 
3: 2
4: 
5: 1
1: image 231
0: 
1: 1
2: 
3: 2
4: 
5: 1

问题根源

问题出在选择器的范围:当你在.image的.each()回调里使用$('.qty')时,这是一个全局选择器,会选中页面上所有带.qty类的元素,而不是当前遍历的.image容器内的.qty元素。所以每次遍历一个.image,都会把页面中所有6个.qty全部输出一遍。

解决方案

需要将.qty的选择范围限制在当前的.image元素内,使用$(this).find('.qty')来实现——$(this)在.image的.each()回调中代表当前正在遍历的.image容器,.find()方法会只查找该容器内部的.qty元素。

修正后的JS代码:

$(function() {
 $('.image').each(function(index) {
    console.log( index+": "+$(this).attr('class') );
    // 仅查找当前.image下的.qty元素
    $(this).find('.qty').each(function(qtyIndex) {
      console.log( qtyIndex+': '+$(this).val() );
    });
  });
});

这样运行后,输出就会和预期一致:每个.image只遍历自己内部的3个.qty元素,不会全局遍历所有.qty。

内容的提问来源于stack exchange,提问作者breadwild

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:33:37