2014-03-06 50 views
0

我發現很難在iframe中選擇元素,並在我的父頁面中進行一些操作。這是我的代碼,它不起作用。家長從iframe中選擇元素

在我父代碼:

//(JS PART) 
var $currentIFrame = $('#screen'); 
    alert($currentIFrame.contents().find("#abc").type); 

//(body part) 
    <iframe id="screen" name="screen" width="100%" height="100%" src="test.php"> 

        </iframe> 

在我的iframe文件:

//(body part) 
<input type="text" id="abc" name="abc"> 

雖然結果是 「不確定」,而不是 「文本」。

回答

2

您需要使用attr()

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

alert($currentIFrame.contents().find("#abc").attr('type')); 

編輯:如果iframe是不同的領域,你不能訪問它的內容由於Same-origin policy

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin " http://fiddle.jshell.net " from accessing a frame with origin " http://www.ebay.com ". Protocols, domains, and ports must match.

+0

我不知道爲什麼這樣做,我們需要在這裏使用.contents()..? –

+0

訪問iframe的內容。 – Felix

+0

答案就是,.find()..的目的是什麼? - >它用於查找元素.. ***我在這方面要求發現自己的權利..? –

3

,你需要使用.attr()

alert($currentIFrame.contents().find("#abc").attr('type')); 
+0

我不知道爲什麼....它仍然未定義... – WillDo

+0

這應該工作。你可以把小提琴弄成問題嗎? –

+0

我做了一個ebay的例子:jsfiddle.net/PL2Qy – WillDo

1

嘗試使用發現

var element = $currentIFrame.find("#abc").attr('type')); 
+0

我做了一個測試,但你的答案都不行。在這裏,我使用易趣只是爲了測試,它應該返回「複選框」,但沒有任何回報:http://jsfiddle.net/PL2Qy/ – WillDo

1

你應該在2個因素要注意:

  • 1 - 框架應該是來自同一個域,否則你什麼都不能做 ;
  • 2 - 當您嘗試獲取iframe中的元素時 - 必須已加載 。

var frame = $('#frameSelector'); frame.load(function(){ var element = frame.contents().find('.selector'); });