2015-09-26 110 views
-2

是否有可能使用Javascript或Jquery重新计算货币。Javascript货币转换

例如:

<div id="price">$99.00</div> 

将改为

<div class="gbp" id="price">£63.85</div> 

如果一个类 “英镑” 的被应用于div标签?

+3

应用类别时,您必须手动进行转换 – Tushar

+4

确实有可能。你试过了吗?什么不起作用?看看[如何问一个好问题](http://stackoverflow.com/help/how-to-ask) –

+0

这是非常简单的获取和更改文本。问题是真的缺乏细节和研究努力的迹象 – charlietfl

回答

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); 
 
    } 
 
})();
<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>

正如你可以看到,该按钮的事件处理程序只改变的inputclassName

btn.addEventListener('click', function(e) { 
    price.className = this.id; 
}); 

observer得到这个改变,并为你做转换。