javascript實現網頁子頁面遍曆回調的方法(涉及 window.frames、遞迴函式、函數上下文)_javascript技巧

來源:互聯網
上載者:User

本文執行個體講述了javascript實現網頁子頁面遍曆回調的方法(涉及 window.frames、遞迴函式、函數上下文)。分享給大家供大家參考。具體如下:

提煉於本人手寫的純 JavaScript 工具程式,用於遍曆當前網頁的所有子頁面 並執行迭代回調,且回呼函數傳回值可用於結果回傳,有助於減少閉包變數~

其特點在於 —— 遞迴遍曆時只檢索子頁面的 Window 對象,不立即執行回呼函數,而是在檢索結束後在普通迴圈結構中回調。這樣可以盡量減少 遞迴調用時的記憶體消耗,也簡化了程式結構,易於維護

全域函數 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);

使用樣本:

// 無參數 —— 返回一個數組,包含函數調用所在的 Window 對象及其子頁面的 Window,其順序同遞迴遍曆var Pages = Frame_Each();console.log( Pages.length );// 定義回調 —— 回調傳回值功能與普通迴圈語句的對應://  1. undefined:continue//  2. false:break//  3. 其它任何值:break && return Valuevar 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!';

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.