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

我正在建立一个现有的woocommerce 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(''); // 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('
'); // Insert a label: $radio.before( $("

然后我用过这个

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

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

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

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

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

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