2017-05-04 38 views
0

我在Shopify中使用貨幣切換器,問題在於,我正在與之合作的客戶希望每個貨幣欄都使用默認值(GBP)將其價格調整爲最高最接近的整數,所以458.54美元變成459美元。jQuery - 使用多種元素彙總所有貨幣價格

我幾乎可以正常工作,除非有多個.money元素存在,它似乎會中斷並將它們合併在一起。

的JS代碼:

var all = $(".money") 
.map(function() { 
return this.innerHTML; 
}) 
.get(); 

var all = [all, ","]; 
var arrayLength = all.length; 
for (var i = 0; i < arrayLength; i++) { 
    //Do something 
} 
console.log("array:", all); 
var regex = all.toString().replace(/[^0-9.]/g, ""); 

var regex = [regex, ","]; 
var regexarrayLength = regex.length; 
for (var i = 0; i < regexarrayLength; i++) { 
//Do something 
} 
console.log("arrayregex:", regex); 
console.log("regex:", regex); 
var rounded_currency = Math.round(regex); 
console.log("rounded_currency:", rounded_currency); 
$("#update").click(function() { 
    alert(rounded_currency); 
}); 

$(document).ready(function() { 
    $(".priceUpdate").text(regex); 
    $(".priceRound").text(rounded_currency); 
}); 

CodePen Example

+0

爲了圓的價格使用'Math.round(6453.65)「,但不要忘記刪除逗號,否則就西港島線讀取逗號和輪6,而不是6454(編號從CodePen例子) –

回答

0

爲了達到預期的效果,請使用以下選項

更改價格,以圓潤的價格數組的數組,正則表達式是不正確的數組是爲什麼它投擲NaN

更新codepen與日元價值測試

console.log("array:", all); 

    var prices = all[0].map(function(num){ 
     return var prices = all[0].map(function(num){ 
    return Math.round(num.replace(/,/g, '').substr(1)); 
}) 
console.log(prices) 
    }) 
    console.log(prices);//rounded prices [6454,6454,454,644,6564454] 

Codepen- https://codepen.io/nagasai/pen/VbMZBz?editors=1111

+0

這看起來非常棒,非常感謝。 – ConduciveMammal

+0

很高興爲你效勞:) –

+0

嗯實際上,這是生產日元除日元 – ConduciveMammal

0

您可以使用JavaScript的Math.ceil()功能的圍捕到最接近的整數。

例如,使用.money類在所有選擇器的數組上循環並首先剝離美元符號。然後調用Math.ceil()。

var all = $(".money").map(function() { 
    return this.innerHTML; 
}).get(); 
//["$6453.65", "$6453.65", "$453.65", "$643.65", "$6564453.65"] 

var rounded = all.map(function(x) { 
    var numbers = x.replace(/[^0-9]/, ''); 
    return Math.ceil(numbers); 
}); 
//[6454, 6454, 454, 644, 6564454]