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

多组单选按钮状态变更监听:实现可复用的变量更新与请求触发方案

可复用的多组单选按钮状态管理与Fetch触发方案

核心思路

用状态对象统一管理所有单选组的选中值,既可以轻松更新变量,又能实现逻辑复用,任意单选组变更时都能自动触发Fetch请求。

完整实现代码

JavaScript

// 初始化状态对象,存储所有单选组的当前选中值
const formState = {
  subscriptionType: document.querySelector('.membership-type-radio:checked').value,
  duration: document.querySelector('.duration-radio:checked').value
};

// 通用Fetch请求函数,直接使用当前状态对象的数据
async function fetchData() {
  try {
    const response = await fetch('你的请求目标URL', {
      method: 'POST', // 根据需求调整为GET/PUT等
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formState)
    });
    const data = await response.json();
    console.log('请求返回结果:', data);
    // 此处可添加返回数据的处理逻辑,比如更新页面内容
  } catch (error) {
    console.error('请求失败:', error);
  }
}

// 给所有目标单选按钮绑定变更事件
const radioInputs = document.querySelectorAll('.membership-type-radio, .duration-radio');
radioInputs.forEach(input => {
  input.addEventListener('change', (e) => {
    // 通过单选按钮的name属性匹配状态对象的键,自动更新对应值
    formState[e.target.name] = e.target.value;
    // 触发Fetch请求
    fetchData();
    // 可选:打印当前状态,验证更新是否生效
    console.log('当前选中状态:', formState);
  });
});

// 页面加载完成后可主动触发一次初始请求(按需启用)
// fetchData();

HTML(保持原有结构即可)

<div class="step">
    <h2 class="step-title">Abonnement</h2>
    <div class="membership-options-container">
        <input type="radio" name="subscriptionType" value="daluren" class="membership-type-radio" id="daluren" checked />
        <label for="daluren" class="btn-label">Daluren</label>
        <input type="radio" name="subscriptionType" value="Premium" class="membership-type-radio" id="premium" />
        <label for="premium" class="btn-label">Premium</label>
    </div>

    <div class="memberships-container">
        <p>test</p>
    </div>
</div>
<div class="step">
    <h2 class="step-title">Looptijd</h2>
    <div class="duration-box">
        <input type="radio" name="duration" value="104" class="duration-radio" id="104" checked />
        <label for="104" class="btn-label">104 Weken</label>
        <input type="radio" name="duration" value="52" class="duration-radio" id="52" />
        <label for="52" class="btn-label">52 Weken</label>
        <input type="radio" name="duration" value="4" class="duration-radio" id="4" />
        <label for="4" class="btn-label">4 Weken</label>
    </div>
</div>

CSS(保持原有样式即可)

.duration-box {
    display: flex;
    justify-content: space-between;
}

.duration-box .btn-label {
    flex-basis: 32%;
}

.btn-label {
    border: 2px solid var(--purple);
    color: var(--purple);
    text-align: center;
    height: 50px;
    border-radius: 10px;
    line-height: 50px;
}

.btn-label:hover {
    background-color: var(--purple);
    color: blue;
    cursor: pointer;
}

.membership {
    color: red;
}

.membership-options-container {
    display: flex;
    justify-content: space-between;
}

.membership-options-container .btn-label {
    flex-basis: 49%;
}

.membership-type-radio, .duration-radio {
    margin: 0;
    display: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

.membership-type-radio[type="radio"]:checked + .btn-label,
.duration-radio[type="radio"]:checked + .btn-label {
    background-color: var(--purple);
    color: red;
}

原方案失效原因说明

  • 第一种方案:只能单独处理某一组单选按钮,新增组时需要重复编写事件监听逻辑,复用性极差。
  • 第二种方案:使用window[e.target.name]更新变量,但let声明的subscriptionType和duration是局部变量,并不挂载在window对象上,因此无法通过这种方式更新。状态对象则完美规避了这个问题,同时支持无限扩展单选组。

扩展提示

如果后续新增其他单选组,只需两步即可适配:

  1. 在formState中添加对应初始值(从DOM获取选中项)
  2. 给新增的单选按钮添加对应的类名(或直接把选择器改成input[type="radio"],监听所有单选按钮)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:41:07