2016-05-16 2 views
-5

Я хочу знать, как этот код JavaScript находит эти текстовые строки («aaa», «bbb» и «ccc») на моей странице.Как этот javascript-код разворачивается?

Каждый из них отделен в коде.

Спасибо

Вот код:

function ae(func) { 
    var oldonload = window.onload; 
    if (typeof oldonload != 'function') { 
     window.onload = func; 
    } else { 
     window.onload = function() { 
     oldonload(); 
     func(); 
     } 
    } 
    } 
    function qw(e, t, n) { 
    if (e && "undefined" != typeof t)for (var r = "string" == typeof e ? new RegExp(e, "g") : e, a = (n || document.body).childNodes, d = a.length, i = "html,head,style,title,link,meta,script,object,iframe"; d--;) { 
     var o = a[d]; 
     if (1 === o.nodeType && -1 === (i + ",").indexOf(o.nodeName.toLowerCase() + ",") && arguments.callee(e, t, o), 3 === o.nodeType && r.test(o.data)) { 
     var l = o.parentNode, c = function() { 
      var e = o.data.replace(r, t), n = document.createElement("div"), a = document.createDocumentFragment(); 
      for (n.innerHTML = e; n.firstChild;)a.appendChild(n.firstChild); 
      return a 
     }(); 
     l.insertBefore(c, o), l.removeChild(o) 
     } 
    } 
    } 
    ae(fg); 
    function fg() { 
    qw('aaa', 'a'); 
    qw('bbb', 'b'); 
    qw('ccc', 'c'); 
    }`` 
+0

вы можете добавить более подробную информацию о коде –

+0

ответ на ваш вопрос требует много ума власти, но не дает никакой ценности для общества ... так что вы находитесь в опасности быть жертвой отрицательной головокружения, только потому, что такие вопросы не приветствуются здесь. – webdeb

+0

Даже если этот код гений, вы не должны так программировать. Причина этого заключается в том, что этот стиль кодирования невозможно отладки. – Steffomio

ответ

0

нормально, так что давайте разбить его как можно лучше.

// ------------------------- 
// add an additional step (function) to the onload handler. 
// ------------------------- 
function ae(func) { 
    // ------------------------- 
    // save the current onload handler to a variable 
    // ------------------------- 
    var oldonload = window.onload; 
    // ------------------------- 

    // ------------------------- 
    // meld the current onload and the new "func" together. 
    // ------------------------- 
    if (typeof oldonload != 'function') { 
     window.onload = func; 
    } else { 
     window.onload = function() { 
     oldonload(); 
     func(); 
    } 
    // ------------------------- 
} 
// ------------------------- 

Работа ае() является «добавить» свой параметр (функция) в обработчик окна OnLoad.

// ------------------------- 
// call qw() a few times 
// ------------------------- 
function fg() { 
    qw('a', 'a'); 
    qw('b', 'b'); 
    qw('ccc', 'c'); 
} 
// ------------------------- 

фг() просто вызывает КЯ() несколько раз ...

// ------------------------- 
// add a function "fg" to the onload handler 
// ------------------------- 
ae(fg); 
// ------------------------- 

На данный момент то, что мы имеем функция фг() будут добавлены к окнам OnLoad() спасибо к работе ae(). В конечном счете, onload, qw() будет выполняться три раза (в дополнение к любой другой работе, уже определенной для onload ...

Это оставляет нас с qw(), который я расширил и реструктурировал для ясности ...

// ------------------------------- 
// "e" regex pattern 
// "t" replacement string 
// "n" root node 
// ------------------------------- 
// under "n" defaulting to <body /> recursively find text nodes 
// and apply the regex pattern "e" to search and place with "t" 
// ------------------------------- 
function qw(e, t, n) { 
    // ------------------------------- 
    // if the parameters are not good, abort 
    // ------------------------------- 
    if (!e || "undefined" === typeof t) { return; } 
    // ------------------------------- 

    // ------------------------------- 
    // "a" holds child nodes of <body /> 
    // unless we passing in a new parent as parameter "n" 
    // ------------------------------- 
    var a = (n || document.body).childNodes; 
    // ------------------------------- 

    // ------------------------------- 
    // d indicates how many nodes we found 
    // ------------------------------- 
    var d = a.length; 
    // ------------------------------- 

    // ------------------------------- 
    // "i" holds a list of tags that we will not process as we will discover later 
    // ------------------------------- 
    var i = "html,head,style,title,link,meta,script,object,iframe"; 
    // ------------------------------- 

    // ------------------------------- 
    // if "e" is a string "r" shall hold a regex based on "e" 
    // otherwise "r" shall hold "e" 
    // ------------------------------- 
    var r = (("string" == typeof e) ? new RegExp(e, "g") : e); 
    // ------------------------------- 

    // ------------------------------- 
    // do until d === 0 
    // i.e. do once for each child node identified above... 
    // ------------------------------- 
    for (; d--;) { 
     // ------------------------------- 
     // o shall be the "current" child node 
     // ------------------------------- 
     var o = a[d]; 
     // ------------------------------- 

     // ------------------------------- 
     // cnd1 shall indicate if "o" is an "Element" (div, p, ...) 
     // ------------------------------- 
     var cnd1 = (1 === o.nodeType); 
     // ------------------------------- 

     // ------------------------------- 
     // cnd2 shall indicate if "o" is not in the list "i" 
     // ------------------------------- 
     var cnd2 = (-1 === (i + ",").indexOf(o.nodeName.toLowerCase() + ",")); 
     // ------------------------------- 

     // ------------------------------- 
     // The comma operator is intentionally messing with us! 
     // if "o" is an Element but not a "bad" one recurse 
     // ------------------------------- 
     if (cnd1 && cnd2) { arguments.callee(e, t, o); } 
     // ------------------------------- 

     // ------------------------------- 
     // "cnd3" shall indicate if "o" is actual text 
     // ------------------------------- 
     var cnd3 = (3 === o.nodeType); 
     // ------------------------------- 

     // ------------------------------- 
     // "cnd4" shall indicate if "o" matches our regex "r" 
     // ------------------------------- 
     var cnd4 = (r.test(o.data)); 
     // ------------------------------- 

     // ------------------------------- 
     // if "o" is not the text part of a node or if it is but not a hit then move on 
     // ------------------------------- 
     if (!cnd3 || !cnd4) { continue;) 
     // ------------------------------- 

     // ------------------------------- 
     // Get the parent of this text (the prior "o") 
     // ------------------------------- 
     var l = o.parentNode; 
     // ------------------------------- 

     // ------------------------------- 
     // "c" will be a collection of text nodes (single) the result of a search and replace based on the initial parameters 
     // ------------------------------- 
     var c = function() { 
      // ------------------------------- 
      // NOTE: after this point local "e" scopes parameter "e" 
      // in this context "e" is now the results of our search and replace 
      // ------------------------------- 
      var e = o.data.replace(r, t); 
      // ------------------------------- 

      // ------------------------------- 
      // create a template div to hold our new text "e" 
      // in turn this will allow us to essentially convert "e" to a node 
      // ------------------------------- 
      var n = document.createElement("div"); 
      n.innerHTML = e; 
      // ------------------------------- 

      // ------------------------------- 
      // "a" shall be a container for new child nodes 
      // ------------------------------- 
      var a = document.createDocumentFragment(); 
      // ------------------------------- 

      // ------------------------------- 
      // note sure if there are ever any more than 1 but this 
      // moves all the children of "n" to be children of "a" 
      // ------------------------------- 
      for (; n.firstChild;) { a.appendChild(n.firstChild); } 
      // ------------------------------- 

      // ------------------------------- 
      // return our new node container with the results of the search and replace 
      // ------------------------------- 
      return a 
      // ------------------------------- 
     }(); 
     // ------------------------------- 

     // ------------------------------- 
     // add the results node "c" to the parent just prior to the current "o" 
     // ------------------------------- 
     l.insertBefore(c, o); 
     // ------------------------------- 

     // ------------------------------- 
     // now remove from the parent the current "o" 
     // ------------------------------- 
     l.removeChild(o) 
     // ------------------------------- 

     // ------------------------------- 
     // effectively we have replaced "o" with "c" 
     // ------------------------------- 
    } 
} 
// ------------------------------- 
Смежные вопросы