2009-08-03 22 views
3

我需要在同一個iframe中選擇一個帶有jQuery查詢的iframe。但是,我不想分配iframe一個唯一的ID和使用如何從jquery自身選擇一個iframe

$('#'+self.name,top.document) 

(我看到某處)。是否有任何相對的方式來做到這一點(與$(this)和遍歷??!?)

一切都在同一臺服務器上,沒有xss。

回答

24

如果您的網站上只有一個iFrame,很容易。只要使用這個選擇器

$('iframe', parent.document) 

如果你有多一個,它會變得更加複雜。 iFrame文檔沒有關於它加載哪個主頁面iframe的線索,所以沒有簡單的方法用選擇器選擇父iframe。如果您知道父ID,名稱,類別或者甚至是iframe源URL,則可以使用該信息修改上面的選擇器以僅匹配所需的iframe。如果你知道它在主頁上的索引,你也可以匹配你需要的iframe。

// iframe with MyClass class 
$('iframe.MyClass', parent.document); 

// iframe with MyId id 
$('iframe#MyId', parent.document); 
// even better since id is unique 
$('#MyId', parent.document); 

// iframe with myname name 
$('iframe[name=myname]', parent.document); 

// iframe with specific src 
$('iframe[src=/path/to/iframe/source]', parent.document); 

// second iframe (index is starting from 0) 
$('iframe:eq(1)', parent.document); 
+0

感謝您的詳細響應。我以爲我忽略了一些東西,但現在我發現它沒有簡單的方法。 – Rado 2009-08-03 20:25:36

2

要選擇它必須是第二iframe中:

second iframe (index is starting from 0) 
$('iframe:eq(1)', parent.document);