下拉菜单转换为单选按钮,不再触发特定功能

Dropdown converted to radio buttons, no longer triggering specific function

本文关键字:功能 不再 转换 单选按钮 下拉菜单      更新时间:2023-09-26

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

我用这个把输入转换成无线电(从这里):

$('.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);
});

这样,当选择收音机时,它会在下拉选项中镜像事件。这很好,但不会触发产品信息的刷新。我的猜测是,更改下拉选项的"selected"属性和物理地单击同一个选项是有区别的。有没有人猜测是什么事件触发了我没有考虑的ajax函数?还有一个理想情况下不需要修改wooccommerce原始代码的解决方案?我试过在select选项上使用.click(),但没有什么区别。

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

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

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

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