一般来说:
- 要处理很多事情,请使用数组:
[blah1, blah2, etc.]
- 要将 ad-hoc 值关联到 ad-hoc 标签,请使用对象:
[ {blah1: 3.1}, {blah2: 415}, etc.]
- 要检测和操作页面上的内容,请使用jQuery。
- 要向页面添加显示或其他元素,也可以使用 jQuery。
总而言之,这是一个完整的脚本,可以完成您的问题似乎要问的问题。您还可以在 jsFiddle 上查看运行中的代码。:
// ==UserScript==
// @name Arbitrary math on arbitrary page values
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var textToValuesArray = [
{"doctor": 3}
, {"lawyer": 5}
, {"rodeo clown": 7}
// etc.
];
var targetNodes = $("td.left:has(a)");
var targetText = targetNodes.text ();
var reportValue = 0;
//-- Loop through the textToValuesArray.
$.each (textToValuesArray, function (index, textToValueObject) {
var textTerm = Object.keys (textToValueObject)[0];
//-- Is the text term in the targeted part of the page?
var termRegex = new RegExp(textTerm, 'i'); // Case insensitive
if (termRegex.test (targetText) ) {
console.log ("Text '" + textTerm + "' was found!");
/*-- Given the indicated page structure, targetText will look like:
"doctor (2)lawyer (4)" etc.
With the value we want coming one space after the target term
and in parentheses.
So, if we split the string on the search term, we get the next
(number), if any.
*/
var splitStr = targetText.split (termRegex);
if (splitStr && splitStr.length > 1) {
var multiplierString = splitStr[1].replace (/^\s*\((\d+)\).*$/, "$1");
if (multiplierString) {
var multiplierInteger = parseInt (multiplierString, 10);
if (isNaN (multiplierInteger) ) {
console.log ("Multiplier value not found! (2)");
}
else {
/*-- We found a term and we found its multiplier.
Add to the report value.
*/
var termValue = textToValueObject[textTerm];
console.log (
"termValue: ", termValue,
" ",
"multiplierInteger: ", multiplierInteger
);
reportValue += termValue * multiplierInteger
}
}
else {
console.log ("Multiplier value not found! (1)");
}
}
else {
console.log ("Split string error!");
}
}
} );
console.log ("reportValue: ", reportValue);
$("body").prepend ('<div id="gmReport">The final value was: ' + reportValue + '</div>');
$("#gmReport").css ("background", "orange");