2015-10-30 59 views
1

我正在爲一個複雜的頁面而努力以選擇少量元素。主要的是我需要讀取/改變輸入值的形式。 到目前爲止我獲得成功,形成使用此代碼:contentDocument的內容()會返回空值

var mainFrame = $(frames[1].document.body).contents().find("#mainFrame1"); 

好了,所以我嘗試:

$(mainFrame.contents()); 

,並返回空[] ...如果我嘗試

$(mainFrame[0].contents()); 

我得到的錯誤:mainFrame [0] .contents不是一個函數...

但使用純JS:

mainFrame[0].contentDocument.getElementById("dataForm"); 

作品! 我想把它保存到jQuery中,我需要在這個相同的框架內找到更多的元素,所以我需要mainFrame變量可用於搜索所有這些元素...

試圖幫助下面的答案找到一個完整的解決方案,我張貼console.debug大型機變量:

console.debug(mainFrame); 
[frame#mainFrame, prevObject: b.fn.b.init[7], context: frameset#outerFrameSet, selector: "#mainFrame"] 
0: frame#mainFrame 
    accessKey: "" 
    attributes: NamedNodeMap 
    baseURI: "https://edited" 
    childElementCount: 0 
    childNodes: NodeList[0] 
    children: HTMLCollection[0] 
    classList: DOMTokenList[0] 
    className: "" 
    clientHeight: 369 
    clientLeft: 0 
    clientTop: 0 
    clientWidth: 1150 
    contentDocument: document 
          ->body 
            ->children (here I can see the form I'm trying to select) 
    contentEditable: "inherit" 
    contentWindow: Window 
    dataset: DOMStringMap 
    dir: "" 
    draggable: false 
    firstChild: null 
    firstElementChild: null 
    frameBorder: "0" 
    hidden: false 
    id: "mainFrame" 
    innerHTML: "" 
    innerText: "" 
    isContentEditable: false 
    ... 
    outerHTML: "<body ..." 
    continues... 
+0

您不能在DOM節點上運行'.contents();'。 – KingCodeFish

回答

2

$(mainFrame.contents());作品,因爲mainFrame是一個jQuery對象。 jQuery方法只能應用於jQuery對象。

$(mainFrame[0].contents());產生錯誤,因爲mainFrame[0]mainFrame jQuery對象返回DOM節點。因此,您不能在其上使用$.contents

爲了解決這個問題,我們可以把它改寫像這樣:

$(mainFrame[0]).contents(); 

這需要的DOM節點,將其轉換回一個jQuery對象,從而使我們能夠在其上運行$.contents();。現在很明顯,當試圖將所有這些用作另一個jQuery對象時,這會變得麻煩:$($(mainFrame[0]).contents());。由於其中的一些原因,您有類似$.first();的方法,而不是返回DOM節點的數組。您也有CSS :first-child選擇器。

最終,要使用$.contents();,您必須針對它使用jQuery對象,而不是使用mainFrame[0]返回的DOM節點。你的最終JavaScript版本工作,因爲JS的功能是建立與DOM節點的工作,但jQuery與對象工作。

+0

好吧,但問題仍然是,你給我的解決方案,返回一個空的對象[],而'mainFrame [0] .contentDocument'返回正確的值... – user3810691

+0

'$(mainFrame.contents());'和' $(mainFrame [0])。contents();'返回空[] – user3810691

+0

我可以在你的問題中有一個例子或代碼的鏈接,這個表單看起來像什麼。因爲你的'mainFrame'似乎不必要的複雜。 – KingCodeFish