开发者

How would this code be refactored to use jQuery?

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:

  1. Context: aThis.document
  2. Selection: //span[@class='emleOnLoad']
  3. Iteration: for (var jj=0; jj<result.snapshotLength; jj++)
  4. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜