是否可以使用Javascript或Jquery重新计算货币。
例如:
<div id="price">$99.00</div>
将更改为
<div class="gbp" id="price">£63.85</div>
如果将一个“GBP”类应用于div标签?
答案 0 :(得分:3)
您可以使用MutationObservers执行此操作:
(function() {
var observer = new MutationObserver(function(mutations) {
// for the class attribute, only the last mutation is important
var mutation = mutations[mutations.length - 1],
el = mutation.target;
calculatePrice(el);
});
var config = {
attributes: true,
attributeFilter: ['class']
};
document.addEventListener('DOMContentLoaded', function() {
var price = document.querySelector('#price');
observer.observe(price, config);
[].forEach.call(document.querySelectorAll('button'), function(btn, i) {
btn.addEventListener('click', function(e) {
price.className = this.id;
});
});
});
function calculatePrice(el) {
var currencies = {
usd: 1,
gbp: 0.65,
brl: 3.90
};
var types = {
usd: '$',
gbp: '£',
brl: 'R$'
};
var currentType = Object.keys(types).filter(function(t) {
return el.textContent.slice(0, types[t].length) === types[t];
});
currentType = currentType[0];
var newType = el.className;
var vl = Number(el.getAttribute('data-price')) * currencies[newType];
el.textContent = types[newType] + vl.toFixed(2);
}
})();
&#13;
<div id='price' data-price='99' class='usd'>$99.00</div>
<button id='usd'>Change the class to 'usd'</button>
<button id='gbp'>Change the class to 'gbp'</button>
<button id='brl'>Change the class to 'brl'</button>
&#13;
如您所见,按钮的事件处理程序仅更改className
的{{1}}:
input
btn.addEventListener('click', function(e) {
price.className = this.id;
});
获得了更改,并为您进行转换。