如何重构此代码以使用jQuery?

时间:2010-03-26 04:13:36

标签: javascript jquery

如何重构此代码以使用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);
  }
}

jQuery似乎有四个问题需要解决:

  1. 上下文:aThis.document
  2. 选择://span[@class='emleOnLoad']
  3. 迭代:for (var jj=0; jj<result.snapshotLength; jj++)
  4. 价值:.textContent
  5. 代码是来自Emle - Electronic Mathematics Laboratory Equipment JavaScript文件emle_lab.js的片段。

    .evaluate()函数会抓取所有<span>个具有类emleOnLoad的标记。生成的文本内容包含表达式片段,例如:

    emleHandleInput(emleThis.parentNode.parentNode,"EMLE_CET_PROPER_FRACTION");
    

    附加到:

    var emleThis=result.snapshotItem(jj);
    

    然后对.evaluate()函数找到的每个项执行。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

你不需要jQuery,但我会用这个替换开关:

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] || '';
  };
})();

首先,我创建一个匿名函数并调用它以便我可以声明局部变量,否则TYPES将最终(可能)全局范围。然后我创建一个对象(map / hash),它就像你的开关那样映射值。最后,创建另一个匿名函数,该函数在TYPES中查找前缀,默认为''。

剩下的就搞砸了。

相关问题