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

根据单选框选择将data-name属性值存入对应数组的实现问题

解决单选框选择后维护出席/缺席数组的问题

需求说明

  • 选择单选框的yes选项时,将对应input元素的data-name属性值推入accepted_array数组
  • 选择no选项时,将该值存入declined_array数组
  • 支持多人选择,数组需正确累积数据
  • 切换选择时(如从yes改为no),需将名称从原数组移除并加入目标数组

对应HTML结构

<div class="guest__options-group">
  <input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
  <label for="attending-yes-0">Yes</label>
</div>

<div class="guest__options-group">
  <input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
  <label for="attending-no-0">No</label>
</div>

<!-- options for Alex -->

<div class="guest__options-group">
  <input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
  <label for="attending-yes-1">Yes</label>
</div>

<div class="guest__options-group">
  <input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
  <label for="attending-no-1">No</label>
</div>

原有实现的问题分析

第一种实现的问题

  • accepted_array和declined_array在点击事件内部声明,每次触发事件都会重新创建空数组,无法累积数据
  • 控制台输出时错误地将declined_array写成accepted_array,导致输出结果混淆
  • 未处理切换选择的场景,无法从原数组移除已存在的名称

第二种实现的问题

  • 错误地将data作为数组却使用对象键值方式存储,逻辑混乱
  • 同样每次点击都重新创建data变量,无法维护持久状态
  • 未区分出席和缺席两个数组,不符合需求

正确实现方案

(function ($) {
  // 在闭包内声明持久化的数组,避免全局污染同时保持状态
  let accepted_array = [];
  let declined_array = [];

  // 封装工具函数:从数组中移除指定元素
  const removeFromArray = (arr, item) => {
    const index = arr.indexOf(item);
    if (index !== -1) {
      arr.splice(index, 1);
    }
  };

  // 监听所有单选框的change事件(比click更准确,仅在选中状态变化时触发)
  $('input[type="radio"][name^="attendance-"]').on('change', function() {
    const $this = $(this);
    const name = $this.data('name');
    const value = $this.val();

    // 先把名字从两个数组中移除,避免重复或错误残留
    removeFromArray(accepted_array, name);
    removeFromArray(declined_array, name);

    // 根据当前选中的值加入对应数组
    if (value === 'yes') {
      accepted_array.push(name);
    } else if (value === 'no') {
      declined_array.push(name);
    }

    // 打印结果验证
    console.log('accepted: ' + accepted_array.join(','));
    console.log('declined: ' + declined_array.join(','));
  });
})(jQuery);

实现说明

  1. 将两个数组放在闭包顶层,确保每次事件触发时都能复用同一个数组实例,维护持久状态
  2. 使用change事件替代click,因为单选框只有在选中状态变化时才会触发,更符合需求逻辑
  3. 每次处理时先移除名字在两个数组中的存在,确保切换选择时不会出现重复或残留数据
  4. 封装removeFromArray函数,简化数组元素移除的逻辑

测试场景验证

  • 场景1:John选yes,Alex选yes → accepted_array = ["John", "Alex"],declined_array = []
  • 场景2:将John改为no → accepted_array = ["Alex"],declined_array = ["John"]
  • 场景3:将Alex改为no → accepted_array = [],declined_array = ["John", "Alex"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:35:21