我想要做的是通過使用iframe從服務器端拉文件到客戶端。iframe和通過jquery附加事件
下面的代碼會收到一個帶有指向服務器上文件路徑的json字符串。如果文件存在,該文件被下載,如果失敗,它應該提醒我。警報功能不起作用。這是因爲我無法附加'加載'事件。 負載事件處理程序應該給我的iframe的內容,但不會發生。爲什麼?我在控制檯收不到任何東西。 var file_directory =「http:// localhost/test /」;
$.getJSON('http://localhost/file.php', function(data) {
for(index in data) {
if(data[index]=='.' || data[index]=='..')
continue;
console.log(file_directory+data[index]);
var frame= $('<iframe />'); // Create an iframe element
$('<iframe />', {
name: 'frame1',
id: 'frame1'+index,
src: file_directory+"d"+data[index]
}).appendTo('body');
$('body').on('onload',frame,function() {
console.log(1);
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = frame.contentDocument || frame.contentWindow.document;
console.log(doc);
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain TypeError:Cannot read property 'document' of undefined
alert('exception: ' + e);
}
});
}
});
$( '身體')上( 'onload事件',框架,函數(){< - 。這似乎不可思議看起來像你試圖做一個在這種情況下,它會'加載'而不是'onload',你不能使用委託綁定。load事件不會冒泡。你需要綁定iframe本身。 – Taplar
'frame'不會出現被追加到文檔中? – guest271314