You need to enable JavaScript to run this app. jQuery如何仅获取触发按钮所属最近父容器内的复选框值
优惠活动
大模型
产品
解决方案
定价
更多

jQuery如何仅获取触发按钮所属最近父容器内的复选框值

修复方案

跨区域收集复选框值的问题,根源是当前的复选框选择器做了全局匹配,没有绑定到按钮所属的容器上。只需要把查找范围限定在当前对应的.destinations容器内,就能避免其他区域的选中值被纳入结果,且不需要编写冗余代码。

核心修改点

你已经通过代码:

var destination = $(this).closest('.destinations');

拿到了当前点击按钮所属的容器元素,只需要在查找复选框时,基于这个容器做范围限定。

把原来的全局选择器:

$.each($("input[name='add_on']:checked"), function(){

替换为基于容器的查找逻辑:

$.each(destination.find("input[name='add_on']:checked"), function(){

这个写法的效果:

  • 只会抓取当前按钮所在div内的选中复选框,其他同name、位于别的.destinations容器的选中项不会被收集
  • 完全复用现有事件绑定逻辑,不需要为每个目的地单独写处理代码
  • destination本身已经是jQuery对象,不需要二次包裹即可直接调用find方法,之前代码里的$(destination)属于多余操作,可以去掉简化逻辑

修改后的完整代码

$(document).ready(function() {
    $('button').on('click', function() {
        var destination = $(this).closest('.destinations');
        var base_price = destination.find('.base_price').text();
        var add_ons = [];
        $.each(destination.find("input[name='add_on']:checked"), function(){
            add_ons.push($(this).val());
        });
        $(this).remove();
        console.log(base_price);
        console.dir(add_ons);
    });
});

需要注意的HTML规范细节

当前页面存在id重复问题:

  • 所有目的地块内的复选框都复用了option1/option2/option3作为id
  • HTML规范要求id在全页面必须唯一,重复id会导致label标签关联错误
  • 后续可以把id修改为带目的地标识的唯一值,比如nyc-option1、paris-option1、tokyo-option1,同步修改对应label的for属性即可,不会影响当前的取值逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 13:36:08