2012-05-03 68 views
0

我用普通的javascript創建了一個iframe。因爲iframe是JQuery和JQuery一起使用的Jquery函數。代碼可以像預期的那樣在iframe中工作。我想讓父頁面執行該功能,而不是在iframe中。雖然創建iframe的代碼可以在任何站點上運行,但iFrame和所有內容都是從同一個域加載的。例如,如果siteB,siteA運行了代碼,則siteA & B可以爲siteZ的網站內容創建iframe。從iframe中調用jquery函數到常規javascript

下面的代碼,從而遠離,我想在父頁面運行的iframe:

<script> 
$(document).ready(function(){      
    $().intad({ 
     title: "blahblah", 
     url: "http://www.blah.com", 
     timeout: 30, 
     deplay: 2, 
     wait: 3, 
     closeable: true 
    }); 
}); 
</script> 

我想這從IFRAME:

<script> 
$(document).ready(function(){      
    function intad(){ 
     title: "blahblah", 
     url: "http://www.blah.com", 
     timeout: 30, 
     deplay: 2, 
     wait: 3, 
     closeable: true 
    }); 
}); 
</script> 

這從代碼,加載到父頁面:

<script> 
parent.document.getElementById("RandomIdHere").contentWindow.intads(); 
</script> 

回答

1

在iFrame中,您需要將您希望調用的函數放在第e window對象,因此它是全局訪問的。

一旦它在那裏,從您的主要頂級html頁面,您可以做iFrameDomElement.contentWindow.yourFunctionToCall()

編輯:

因此,要進一步打破它,你有很多的問題與您的代碼發生。首先,intad是什麼?這是一個jQuery原型的方法嗎?如果沒有,你做錯了什麼。這基本上是你需要做的。

在您的主頁,我將從現在開始調用parent.html。

你需要的東西是這樣的:

// this is a shorthand document ready function 
$(function() { 

    // we will call this from the iframe 
    window.functionInParent = function() { 
     // do your work here 
    }; 

    var iframe = document.createElement('iframe'); 
    iframe.src = 'link/to/iframe/source'; 

    // if you want to talk to the iframe from this parent page, 
    // use this to access the iframe's window object. 
    // just make sure that the function you try to call is on the 
    // window object of the iframe, just like we did with the function above. 
    var iframeWindow = iframe.contentWindow; 
}); 

在你的iframe,你需要的東西是這樣的:

$(function() { 
    // your iframe's dom is ready - do stuff here 

    // once you are ready, call the parent function 
    top.functionInParent(); 
}); 

我希望這有助於。如果您需要進一步的幫助,請將您的工作(或幾乎工作)的代碼放入jsfiddle,以便我可以更好地查看它。

+0

如果您需要從iframe調用您的頂級頁面,請在iframe中使用頂層全局變量訪問主頁面的窗口對象。 – sic1

+0

我該如何從iframe完全做到這一點。你請告訴我工作代碼? – Patriotec

+0

檢查更新,這是如何從你的iframe與你的父頁面交談。 – sic1