How would this code be refactored to use jQuery?
function emleProcessOnLoad(aThis) {
var result = document.evaluate("//span[@class='emleOnLoad']",
aThis.document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var jj=0; jj<result.snapshotLength; jj++){
eval("var emleThis=result.snapshotItem(jj);" + result.snapshotItem(jj).textContent);
}
}
There appears to be four issues for jQuery to address:
- Context:
aThis.document
- Selection:
//span[@class='emleOnLoad']
- Iteration:
for (var jj=0; jj<result.snapshotLength; jj++)
- Value:
.textContent
The code is a fragment from Emle开发者_运维技巧 - Electronic Mathematics Laboratory Equipment JavaScript file emle_lab.js.
The .evaluate()
function grabs all of the <span>
tags which have class emleOnLoad
. The resulting text content contains an expression fragment such as:
emleHandleInput(emleThis.parentNode.parentNode,"EMLE_CET_PROPER_FRACTION");
which is appended to:
var emleThis=result.snapshotItem(jj);
and then is executed for each item found by the .evaluate()
function.
The main loop can be simplified down to this
$("span.emleOnLoad").each(function() {
var content = $(this).text();
// do something with content
});
but the whole idea needs some rethinking. Store chunks of javascript in spans and eval them at run time - this is quite weird.
You don't need jQuery for this, but I would replace the switch with this:
var lu = (function() {
var TYPES = { // call it whatever you want
'xhtml':'http://www.w3.org/1999/xhtml',
'math': 'http://www.w3.org/1998/Math/MathML',
'svg': 'http://www.w3.org/2000/svg'
};
return function luf(aPrefix){
return TYPES[aPrefix] || '';
};
})();
First, I create an anonymous function and call it so that I can declare local variables, otherwise TYPES
will end up in (presumably) global scope. Then I create an object (map/hash) that maps the values just like your switch would. Finally, create another anonymous function that looks the prefix up in TYPES
and defaults to ''.
The rest is pretty messed up.
精彩评论