2013-10-29 21 views
0

我有一個帶有iframe和按鈕的html文件,有沒有方法在點擊按鈕後在iframe正文中添加javascript函數?這是我的代碼。謝謝如何在iframe正文中添加javascript函數

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> 
    <script> 
     function callMe() { 
      var frame = $('iframe'), 
      contents = frame.contents(), 
      body = contents.find('body'); 

    var script2 = document.createElement("script"); 
    script2.type = "text/javascript"; 
    script2.text = " function setEmployeeId(){var employeeId = 0;};"    
    $(body).append(script2); 
     };  
    </script> 



    <title>sample</title> 
</head> 
<body> 
     <iframe src="page2.html">   
     </iframe> 
    <button onClick="callMe();">click</button> 
</body> 
</html> 

我想要的結果就是這樣。

<html> 
<head> 

    <title>sample</title> 
</head> 
<body> 
     <iframe> 
<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <script> 
function setemployeeId() { 
var employeeId = 0; 
}; 
</script> 
</body> 
</html> 
</iframe>  
</body> 
</html> 
+0

該框架的頁面是否在您的域上? –

+0

@AndrewBarber我會假設所以考慮到'src'是相對的「page2.html」。 – zamnuts

+1

你可以在這裏找到你的答案... http://stackoverflow.com/questions/1591135/why-does-appending-a-script-to-a-dynamically-created-iframe-seem-to-run- – gts101

回答

1

希望你能爲我澄清一些事情,因爲我們走了,但我想我有一些壞消息給你。

加載到iframe中的任何內容都無法真正編輯,除非您擁有正在加載的頁面,在這種情況下,您可以根據需要將其加載到加載的頁面中。

不過!

您仍然可以通過使用contentWindow屬性來訪問iframe中的元素。這是你在這裏所有的佈局:How to pick element inside iframe using document.getElementById

一旦你有你想要使用的元素,你可以在父窗口中創建一個函數,然後使用window.parent添加一個調用父窗口的函數。這是這裏概述:所以Calling a parent window function from an iframe

,如果你想使在iframe按鈕改變的iframe你可以使用

var elem = document.getElementById('myframe1').contentWindow.document.getElementById('myButton') 

,然後將內容在你的父窗口創建一個函數

function changeIt(){ 
    document.getElementById('thingToChangeInIframe_ItsIDintheIframe').property = 'value'; 
} 

並將其附加到代碼爲

elem.setAttribute('onclick', 'changeIt();'); 

如果您對需要評論的內容有任何澄清,我們將解決這些問題。我很抱歉,這並沒有使用太多的jQuery,但這並不是我的特長,但我認爲純JavaScript是相對自我解釋的。

編輯:我應該澄清,如果iframe是在另一個域上,那麼你的選擇幾乎全部被淘汰。出於安全原因,當您將它們加載到iframe中時,您不能混淆其他用戶頁面上的設置。

+2

對於跨瀏覽器支持,使用'var y =(x.contentWindow || x.contentDocument); if(y.document)y = y.document;'在[w3schools]上看到(http://www.w3schools.com/jsref/prop_frame_contentwindow.asp) –

+0

非常好的一點。 –

相關問題