我制作了一个greasmonkey脚本,使用API将特定页面中的货币转换为INR。 我能够获得USD-INR的当前货币汇率,并且还能够将货币符号替换为INR,但是无法将货币值转换为当前汇率。我正在使用这个脚本:
$(function(){
GM_xmlhttpRequest({
method: "GET",
url: "http://www.google.com/ig/calculator?hl=en&q=1usd=?inr",
onload: function(d){
d=JSON.stringify(eval("(" + d.responseText + ")"));
d=$.parseJSON(d);
p=Math.round(d.rhs.replace(/[^\d\.]/g, ''));
var replaced=$('body').html().replace(/\$(?:\s+)*(\d+\,\.)?/g, '₹$1');
$('body').html(replaced);
}
});
});
上面的脚本将$ s的所有匹配项替换为Rs。在一个页面中:
$0.50, $1.00, $20.00, $200.00
到
₹0.50, ₹1.00, ₹20.00, ₹200.00
但我想要的是用兑换率兑换货币,如:
₹29.5, ₹59, ₹1180, ₹11800
我没有得到这个......
请帮助..
**OR SOMEONE HAVE BETTER IDEA TO DO THIS CONVERSION. PLZ SUGGEST**
答案 0 :(得分:2)
您需要递归或遍历具有美元值的节点。切勿在{{1}}或replace()
上使用.html()
或RegExp。这不仅会破坏目标页面,而且您将有一段时间获得所需结果。
使用DOM方法递归页面。请注意,货币值有多种格式,因此转换它们会变得复杂。
这里有适合整个页面的强大代码(无iframe)You can see it in action at jsFiddle:
innerHTML
如果这仅适用于几页,请使用jQuery或// ==UserScript==
// @name _Global currency converter, dollars to rupees
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
GM_xmlhttpRequest ( {
method: "GET",
url: 'http://rate-exchange.appspot.com/currency?from=USD&to=INR',
//Google sends malformed response, not JSON.
//url: 'http://www.google.com/ig/calculator?hl=en&q=1usd=?inr',
onload: function (rsp){
var rspJSON = JSON.parse (rsp.responseText);
var convRate = rspJSON.rate;
console.log (rspJSON, convRate);
changeDollarsToRupees (document.body, convRate);
}
} );
function changeDollarsToRupees (node, convRate) {
if (node.nodeType === Node.TEXT_NODE) {
if (/\$/.test (node.nodeValue) ) {
processTextNode (node, convRate);
}
}
else if (node.nodeType === Node.ELEMENT_NODE) {
for (var K = 0, numNodes = node.childNodes.length; K < numNodes; ++K) {
changeDollarsToRupees (node.childNodes[K], convRate);
}
}
}
function processTextNode (node, convRate) {
/*-- Results like:
["Three values: ", "$1.10", " ", "$2.20", " ", "$3.00.", ""]
*/
var moneySplit = node.nodeValue.split (/((?:\+|\-)?\$[0-9.,]+)/);
if (moneySplit && moneySplit.length > 2) {
/*-- Money values will be odd array index, loop through
and convert all.
*/
for (var J = 1, L = moneySplit.length; J < L; J += 2) {
var dolVal = parseFloat (moneySplit[J].replace (/\$|,|([.,]$)/g, "") );
if (typeof dolVal === "number") {
//var rupVal = "Rs" + Math.round (dolVal * convRate);
var rupVal = "Rs" + (dolVal * convRate).toFixed (2);
}
else {
var rupVal = moneySplit[J] + " *Err*";
}
moneySplit[J] = rupVal;
}
//-- Rebuild and replace the text node with the changed value (s).
var newTxt = moneySplit.join ("");
node.nodeValue = newTxt;
}
}
来处理您感兴趣的元素。例如:
document.querySelectorAll()
答案 1 :(得分:1)
我还要求使用Google财经
http://www.google.com/finance/converter?a=1&from=USD&to=INR
上面的链接比http://www.google.com/ig/calculator
更好有些时候Google ig-calculator停止工作,但Google财务始终可用