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

商品页面Radio单选按钮首次加载需点击两次才可触发函数如何解决

问题根因

  • 错误使用attr()操作单选框的checked状态:checked是DOM元素的动态属性(property),不是静态HTML属性(attribute),attr()只能读取初始静态值,和实际选中状态不同步,导致首次点击时判断逻辑失效,需要第二次点击才能让attr()读取到手动设置的值,触发对应逻辑。
  • 手动强制修改单选框checked属性,和浏览器原生单选框互斥逻辑冲突,打乱了状态同步。
  • 两个单选按钮的事件类型不统一,一个绑定click一个绑定change,也会导致首次触发时机不一致。
  • 没有直接读取单选框实际选中状态,而是依赖手动修改的attribute值做判断,逻辑不可靠。

修复方案

删掉所有手动修改单选框checked属性的代码,统一事件绑定逻辑,用原生属性判断选中状态即可,修复后代码如下:

JS代码

//toggle subscription dropdown
const changeOptions = function() {
  // 统一绑定同组所有单选框的change事件
  $("input[name='option']").on('change', function(e) {
    // 直接读取当前实际选中状态即可
    const isSubscribePlan = $("#subscribe_plan").is(':checked');
    if (!isSubscribePlan) {
      // 一次性购买逻辑
      formatName();
      $('.js-price').html('<span class="money">' + (selectedVariant.price / 100).toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }) + '</span>');
      currencyPicker.setCurrencyText();
      Currency.convertAll(shopCurrency, Currency.currentCurrency);

      document.querySelector('.js-selling-plan-id').setAttribute("name", '_');
      document.querySelector('[name="_"]').value = '';
      $('#selling_select').prop("disabled", true);
      $('.subscribe_option').removeClass("d-block").addClass("d-none");
    } else {
      // 订阅方案逻辑
      formatNameSelling();
      const offerPrice = $('.js-price').attr('data-offer-price');
      $('.js-price').html('<span class="money">' + offerPrice + '</span>');
      currencyPicker.setCurrencyText();
      Currency.convertAll(shopCurrency, Currency.currentCurrency);

      const availableSellingPlanAllocations = selectedVariant.selling_plan_allocations;
      const sellingPlan = availableSellingPlanAllocations[0].selling_plan_id;
      document.querySelector('.js-selling-plan-id').setAttribute("name", 'selling_plan');
      document.querySelector('[name="selling_plan"]').value = '';
      $('#selling_select').prop("disabled", false);
      $('.subscribe_option').removeClass("d-none").addClass("d-block");

      $('select').each(function() {
        $(this).val($(this).find("option[selected]").val());
      });
    }
  });
}
//end toggle subscription dropdown

//initiate the function
$(document).ready(function() {
  changeOptions();
  // 如果需要页面加载后自动执行一次当前选中项的逻辑,取消下面一行注释即可
  // $("input[name='option']").trigger('change');
});

HTML代码不需要做任何修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:57:00