【问题标题】:Dropdown converted to radio buttons, no longer triggering specific function下拉转换为单选按钮,不再触发特定功能
【发布时间】:2012-08-02 21:53:08
【问题描述】:

我正在构建一个现有的 woocommerce wordpress 扩展,并将产品变体(尺寸、颜色等)下拉菜单转换为单选框。棘手的是,当用户从下拉列表中选择一个选项时,它会触发一些通过 ajax 自动更新产品库存和价格的东西。

我用它把输入转换成收音机(来自here):

$('.variations select').each(function(i, select){
    var $select = jQuery(select);
    $select.find('option').each(function(j, option){
        var $option = jQuery(option);
        // Create a radio:
        var $radio = jQuery('<input type="radio" />');
        // Set name and value:
        $radio.attr('name', $select.attr('name')).attr('value', $option.val());
        // Set checked if the option was selected
        if ($option.attr('selected')) $radio.attr('checked', 'checked');
        // Insert radio before select box:
        $select.before($radio);
        $radio.wrap('<div class="vari-option fix" />');
        // Insert a label:
        $radio.before(
          $("<label />").attr('for', $select.attr('name')).text($option.text())
        );
    });

那我就用这个了

$(':radio').click(function(){
   $(this).parent().parent().find('label').removeClass('checked');
   $(this).siblings('label').addClass('checked');
   $choice = $(this).attr('value');
   $('.variations select option[value=' + $choice + ']').attr('selected',true);
});

因此,选择无线电时,它会在下拉选项上镜像事件。这工作正常,但它不会触发产品信息的刷新。我的猜测是更改下拉选项的“选定”属性和物理单击同一选项之间存在差异。猜猜什么事件可能会触发我没有考虑到的 ajax 函数?还有一个理想情况下不涉及修改 woocommerce 原始代码的解决方案?我尝试在选择选项上使用 .click() ,但没有任何区别。

【问题讨论】:

    标签: javascript jquery woocommerce


    【解决方案1】:

    以编程方式更改元素的值不会触发change 事件,我假设以编程方式在&lt;option&gt; 上设置selected 属性/属性也不会触发change 事件包含&lt;select&gt; 元素。

    幸运的是,您可以使用 jQuery 以编程方式轻松触发该事件:

    $('.variations select option[value=' + $choice + ']').attr('selected',true).parent().trigger('change');
    

    .parent() 调用返回一个包含&lt;select&gt; 元素的jQuery 对象,然后.trigger('change') 触发绑定到该对象上change 事件的任何事件处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 2012-11-29
      相关资源
      最近更新 更多