gpt4 book ai didi

javascript - 使用 jquery 将页面上的所有价格从一种货币更改为另一种货币?

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:04 25 4
gpt4 key购买 nike

我不需要使用 Yahoo Finance api 等。只需将数字乘以固定数量即可。

See codepen .下拉功能没有实现,我想先把交换下来。我知道这只是一个开始,但如何继续下去呢?这显然需要解决几个问题:

  • 目前这会将每个值更改为相同
  • 我需要能够在再次选择美元时将它们改回
  • 不给出类名,而是自动查找所有价格(包含 $ 或 €)是否效率太低?

你能给我一些指示,我应该如何继续吗?

$(document).ready(function() {
// $('select').material_select();
$('.caret').text(" ");
//here starts my attempt for the exchange
var price = $(".price").text().replace("$", "");
var convertedToNumber = parseFloat(price);
var eurPrice = convertedToNumber / 1.18;
$(".price").text(eurPrice);


});
input.select-dropdown {
color: #26a69a;
}
.caret {
background:url("http://svgshare.com/i/3Bc.svg") no-repeat 90% 50%;
width:20px;
height:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="row">

<div class="input-field col s1">
<select>
<option value="1" selected>USD</option>
<option value="2">EUR</option>
</select>
<label>Currency</label>
</div>
</div>


<ul class="currencies">
<li class="price">$1500</li>
<li class="price">$2000</li>
<li class="price">$342</li>
</ul>

最佳答案

您正在寻找的称为数据绑定(bind),有很多库和东西可以为您提供它。

我会假设你不知道我在说什么,我只会向你解释基本思想是什么。

你有一组数据,在你的例子中是价格。

var prices = [
1500,
2000,
342
];

然后你有你的货币汇率对象

var rates = {
USD: 1, // obviously
EUR: 0.86
}

现在,每次货币更改时,您都会重新计算价格并更新每次出现的情况。

function updatePrices(rate) {
var elements = document.getElementsByClassName("price");

prices.forEach((price, index) => {
elements[index].innerHTML = price * rate
});
}

document.getElementById("selector").onchange = function() {
updatePrices(rates[this.value]);
}

并且最初也调用它。

updatePrices(rates.USD);

现在显然这是一种非常愚蠢的数据绑定(bind)方式,使用数组索引和类名,但这是它背后的基本思想。

至于货币符号,将它们包括在内通常不是一个好主意,因为实际上很少有货币具有它们,但想法是一样的。

var prices = [
1500,
2000,
342
];


var rates = {
USD: 1, // obviously
EUR: 0.86
}

function updatePrices(rate) {
var elements = document.getElementsByClassName("price");

prices.forEach((price, index) => {
elements[index].innerHTML = price * rate
});
}

document.getElementById("selector").onchange = function() {
updatePrices(rates[this.value]);
}


updatePrices(rates.USD);
<div class="row">
<div class="input-field col s1">
<select id="selector">
<option value="USD" selected>USD</option>
<option value="EUR">EUR</option>
</select>
<label>Currency</label>
</div>
</div>


<ul class="currencies">
<li class="price"></li>
<li class="price"></li>
<li class="price"></li>
</ul>

关于javascript - 使用 jquery 将页面上的所有价格从一种货币更改为另一种货币?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46453085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com