Woocommerce产品使用jQuery显示价格操纵

问题描述 投票:1回答:1

基于我的最后一个问题的“Get selected variation price in jQuery on Woocommerce Variable products”答案代码,此代码获取用户对产品选项的输入,我正在尝试使用这些值来计算显示给用户的价格,但我无法弄明白。

除窗口警报消息上方的部分外,所有代码都有效。我试图在警告消息上方的php标签内添加过滤器函数get_price_html(),但它显示了所有类型的错误。

是否可以只使用javascript来更改显示的价格?

这是我实际使用的代码:

add_action( 'woocommerce_before_add_to_cart_quantity', 'func_option_valgt');
function func_option_valgt() {
    global $product;

    if ( $product->is_type('variable') ) {
        $variations_data =[]; // Initializing

        // Loop through variations data
        foreach($product->get_available_variations() as $variation ) {
            // Set for each variation ID the corresponding price in the data array (to be used in jQuery)
            $variations_data[$variation['variation_id']] = $variation['display_price'];
        }
        ?>
        <script>
        jQuery(function($) {
            var jsonData = <?php echo json_encode($variations_data); ?>,
                inputVID = 'input.variation_id';

            $('input').change( function(){
                if( '' != $(inputVID).val() ) {
                    var vid      = $(inputVID).val(), // VARIATION ID
                        length   = $('#cfwc-title-field').val(), // LENGTH
                        diameter = $('#diameter').val(),  // DIAMETER
                        vprice   = ''; // Initilizing

                    // Loop through variation IDs / Prices pairs
                    $.each( jsonData, function( index, price ) {
                        if( index == $(inputVID).val() ) {
                            vprice = price; // The right variation price
                        }
                    });

                    var rope_price = length*vprice;
                    document.cookie = 'rope_price_cookie='+rope_price;

                    ////////// This is where I would like to add some code to change the displayed price //////
                    $('price') = rope_price;  /// something like this, only it doesn't work :(

                    alert('variation Id: '+vid+' || Length: '+length+' || Diameter: '+diameter+' || Variantprice: '+vprice+' ||Rope price: '+rope_price);

                        }
                    }
            });
        });
        </script>
        <?php       
    }   
}

任何帮助赞赏。

php jquery wordpress woocommerce product
1个回答
1
投票

您可以为<span>元素分配ID,例如<span id="price"></span>,然后在JS中执行以下操作:

$("#price").html(rope_price);

请注意,#表示一个ID,您也可以使用类选择器(.price),如果您在页面的多个部分显示价格,这将非常有用。然后,您可以在使用类时更新这些元素(使其成为更具描述性的类,然后price,以防止名称冲突)

© www.soinside.com 2019 - 2024. All rights reserved.