Home  >  Article  >  Web Front-end  >  JavaScript method to implement web page subpage traversal callback (involving window.frames, recursive functions, function context)_javascript skills

JavaScript method to implement web page subpage traversal callback (involving window.frames, recursive functions, function context)_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:48:411801browse

The example in this article describes how JavaScript implements web page subpage traversal callbacks (involving window.frames, recursive functions, and function context). Share it with everyone for your reference. The details are as follows:

Extracted from a pure JavaScript tool program written by myself, it is used to traverse all sub-pages of the current web page and execute iterative callbacks, and the return value of the callback function can be used for result return, helping to reduce closure variables~

Its characteristic is that - only the Window object of the subpage is retrieved during recursive traversal, and the callback function is not executed immediately, but is called back in the ordinary loop structure after the retrieval is completed. This can minimize the memory consumption during recursive calls, simplify the program structure, and make it easy to maintain

Global function Frame_Each( CallBack ):

(function (BOM) {
  function All_Frames(iWindow) {
    var _Frames_ = [].slice.call(iWindow.frames, 0);
    for (var i = 0; i < _Frames_.length; i++)
      _Frames_ = _Frames_.concat( arguments.callee(_Frames_[i]) );
    return _Frames_;
  }
  BOM.Frame_Each = function (CallBack) {
    var Frames = [this].concat( All_Frames(this) );
    if (! CallBack) return Frames;
    for (var i = 0, CBR; i < Frames.length; i++) {
      try { Frames[i].name; } catch (iError) { continue; }
      CBR = CallBack.apply(Frames[i], [].slice.call(arguments, 1));
      if (CBR === false) break;
      else if (CBR === undefined) continue;
      return CBR;
    }
  };
})(self);

Usage example:

// 无参数 —— 返回一个数组,包含函数调用所在的 Window 对象及其子页面的 Window,其顺序同递归遍历
var Pages = Frame_Each();
console.log( Pages.length );
// 定义回调 —— 回调返回值功能与普通循环语句的对应:
//  1. undefined:continue
//  2. false:break
//  3. 其它任何值:break && return Value
var Search_Result = Frame_Each(function () {
  var iFocus = this.document.activeElement;
  switch ( iFocus.tagName.toLowerCase() ) {
    case 'body':   return false;
    case 'iframe':  return;
  }
  return iFocus;
});
Search_Result.innerHTML = 'Hello, Focus!';

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn