这是我们所处位置的一个工作示例:http://fpusa.drunk.kiwi/product/ship-your-idea-2/
我正在尝试为用户点击创建“色板”,这将改变 woocommerce 用来获取变化数据的隐藏选择框的值。
是否有特定的方法告诉 woocommerce 读取选择框的值?
一切都按预期工作,但更改变体 ID 并让所有东西准备好添加到购物车的 javascript 事件从未发生。
注意:我用 d-none 隐藏了 wc_dropdown,因为我认为它会最小化自定义解决方案。
Variable.php - 调用 fpusa_product_attribute_button();
<?php foreach ( $attributes as $attribute_name => $options ) : ?>
<tr class="">
<td class="label"><label for="<?php echo esc_attr( sanitize_title( $attribute_name ) ); ?>"><?php echo wc_attribute_label( $attribute_name ); // WPCS: XSS ok. ?></label></td>
<td class="value">
<?php
fpusa_product_attribute_button( $options, $attribute_name, $product );
wc_dropdown_variation_attribute_options( array(
'options' => $options,
'attribute' => $attribute_name,
'product' => $product,
'class' => 'd-none',
));
echo end( $attribute_keys ) === $attribute_name ? wp_kses_post( apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#">' . esc_html__( 'Clear', 'woocommerce' ) . '</a>' ) ) : '';
?>
</td>
</tr>
<?php endforeach; ?>
fpusa_product_attribute_button()
function fpusa_product_attribute_button( $options, $attribute_name, $product ){
if( ! empty( $options ) ) : ?>
<div id="var_btn" class="d-flex">
<?php foreach( $options as $option ): ?>
<button type="button" class="d-flex btn justify-content-center align-items-center border mx-1" data-key="<?php echo $attribute_name ?>" data-value="<? echo $option ?>">
<?php echo $option; ?>
</button>
<?php endforeach; ?>
</div> <?php
endif;
}
Functions.js
$('#var_btn button').click(function(){
let attribute = $(this).attr('data-key');
let option = $(this).attr('data-value');
console.log( attribute, option );
$('#' + attribute).val( option );
});
最佳答案
我所要做的只是触发 <select>
上的更改事件正在将选定的选项传递给。
$('#var_btn button').click(function(){
let attribute = $(this).attr('data-key');
let option = $(this).attr('data-value');
console.log( attribute, option );
$('#' + attribute).val( option ).change();
});
关于javascript - Woocommerce 通过 JS 更改产品变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54829471/