[英]Wait for iframe to load in JavaScript
我正在用 JavaScript 打開一個 iframe:
righttop.location = "timesheet_notes.php";
然后想向它傳遞信息:
righttop.document.notesform.ID_client.value = Client;
顯然,在頁面完全加載到 iframe 之前,該行不會工作,並且要寫入該表單元素。
那么,解決這個問題的最佳/最有效方法是什么? 某種超時循環? 理想情況下,我真的希望將所有內容都包含在這個特定的腳本中,而不必向正在打開的頁面添加任何額外的內容。
首先,我相信您應該影響 iframe 的src
屬性,而不是location
。 其次,掛鈎 iframe 的load
事件以執行您的更改:
var myIframe = document.getElementById('righttop');
myIframe.addEventListener("load", function() {
this.contentWindow.document.notesform.ID_client.value = Client;
});
myIframe.src = 'timesheet_notes.php';
同樣,這一切都假設您的意思是i框架,而不是框架集。
我想你可以很容易地用 jQuery 做到這一點... jQuery Home只需將頁面掛接到 jQuery $ function ()
... eg
$(document).ready(function() {
$('iframe').load(function() {
// write your code here....
});
});
在這里快速查看文件上傳器示例: Using iframes for multiple file uploads...
iFrame 可以動態加載元素,使用它們的最佳選擇是使用遞歸:
$('iframe').ready(function() {
var triggerMeAgainIfNeeded = function() {
setTimeout(function() {
var neededElm = $('.someElementThatLoadedAfterIframe');
if (neededElm.length > 0) {
// do your job
} else {
triggerMeAgainIfNeeded();
}
}, 10);
}
});
試試這個...
$('iframe').each(function() {
$(this).ready(function() {
$('#result').html("ready");
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.