您需要递归或循环仅通过具有美元值的节点。永远不要在or上使用replace()
or 正则表达式。这不仅会破坏目标页面,而且您将很难获得所需的结果。.html()
innerHTML
使用 DOM 方法在页面中递归。请注意,货币值有多种格式,因此转换它们可能会变得复杂。
这是整个页面的中等健壮代码(无 iframe)您可以在 jsFiddle 看到它的实际效果:
// ==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;
}
}
如果这只是几个页面,请使用 jQuery 或document.querySelectorAll()
只处理您感兴趣的元素。例如:
var targElements = document.querySelectorAll ("div.priceTable");
for (var J = targElements.length - 1; J >= 0; --J) {
changeDollarsToRupees (targElements[J], convRate);
}