[英]Calculate price and display on WooCommerce product single page under price (simple price, variable price)
[英]Price calculation based on dimensions in WooCommerce single product page
基於“ 在Woocommerce變量產品上獲取jQuery中的選定變體價格 ”答案代碼,
在我的代碼中,我對WooCommerce變量產品的價格計算有問題。
價格乘以10或1000,取決於在下拉列表中選擇的選項,這不應該發生,我不知道為什么會發生這種情況。
這是我的代碼:
<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
ene_enden = $('#id_dropdown_one_end').find('option:selected').attr("value_one_end"),
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) + ene_enden;
if (rope_price != 0){
$('.price').html(rope_price+',-');
}
alert('variation Id: '+vid+' || Lengde: '+length+' || Diameter: '+diameter+' || Variantpris: '+vprice+ ' || Rope price: '+rope_price+' || ene_enden = '+ene_enden);
}
});
});
</script>
由於某種原因,當為“我加入”選擇的選項為“Ingenting”時,rope_price將乘以10或與0連接(它的值為0)。 當我將選擇的選項更改為其他任何一個時,rope_price將乘以1000或與00連接。我不知道為什么會發生這種情況。 有任何想法嗎?
因為你是連接字符串。 與"1" + "0"
不同的是1 + 0
,您可以在這里查看:
console.log("1 + 0 =", 1 + 0); console.log('"1" + "0" =', "1" + "0");
從HTML對象獲取值時,將其作為字符串接收。 如果要將其用作數字,則必須先將其轉換。 您可以使用Number
或parseFloat
(甚至是parseInt
,但會刪除小數)。
var oneNumber = 1; var oneString = "1"; var oneConverted = Number(oneString); console.log("typeof oneNumber:", typeof oneNumber); console.log("typeof oneString:", typeof oneString); console.log("typeof oneConverted:", typeof oneConverted); console.log("oneNumber + oneNumber =", oneNumber + oneNumber); console.log('oneString + oneString =', oneString + oneString); console.log('oneConverted + oneConverted =', oneConverted + oneConverted);
您遇到的確切問題是您的ene_enden
變量是行中的字符串var rope_price = (length*vprice) + ene_enden;
。 當你將兩個字符串相乘時,它們會自動轉換為數字(你的(length*vprice)
),但是當你將這個數字連接到另一個字符串時,它們會自動轉換為字符串(你的+ ene_enden
),所以你必須先將ene_enden
轉換為數字,以便將所有預期數字變量轉換為數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.