jBox 是一個不錯的組件庫,可以用來比較簡單地彈出窗口。
我希望在 jBox 彈出窗口之后,自動將焦點設置到子窗口的某個輸入框中,可是發現並不容易。
在 jBox 2.3 中,提供了如下的增強。
[調整] loaded 選項增加了個參數h,參數h表示窗口內容的jQuery對象,方便用戶在窗口加載后對內容進行初始化處理。
示例中並沒有說明 h 的使用方式。
那么,這個 h 是什么呢?
在使用 jBox 的時候,每個彈出的窗口,會創建一個 id 為 jbox-content 的 div 元素包裹所有的窗口內容。在 loaded 中,jBox 傳遞給函數的參數就是這個元素。這個元素的結構如下:
<div style="height: auto; overflow-x: hidden; overflow-y: auto; position: static; left: -10000px;" class="jbox-content" id="jbox-content"> <iframe scrolling="auto" width="100%" height="100%" frameborder="0" marginwidth="0" marginheight="0" id="jbox-iframe" name="jbox-iframe" src="iframe2.html?___t0.9552568292007391"></iframe> </div>
注意這個元素唯一的子元素為一個 iframe 元素,隔斷了 jQuery 的查找。使得我們不能直接找到子窗口中的元素進行處理。
我們可以先找到這個元素的第一個孩子,就是這個 iframe,然后,取出它的名字,通過這個名字找到這個 iframe 對應的窗口,然后,在這個子窗口中查找我們的內容。
代碼如下所示:
$.jBox("iframe:iframe2.html", { loaded: function (h) { var iframeName = h.children(0).attr("name"); var container = window.frames[iframeName].document var elem = $("#username", container); elem.focus(); } });