我正在尝试在网站中创建具有相同来源URL的多个iframe,然后循环遍历每个iframe以访问具有相同ID的元素,并且当前将该元素的innerHTML记录到控制台中。当我单独执行此操作时,它可以工作,但是当我尝试遍历创建的iframe时,在控制台上出现错误。这是chrome扩展程序,我正在通过chrome运行它。
代码:
var iframe;
for (var i = 0; i < num_courses; i++) {
iframe = document.createElement("iframe");
iframe.setAttribute("src", links[i].href);
iframe.id = "i_frame" + i;
// iframe.height = 0;
// iframe.width = 0;
// iframe.style.border = "none";
document.body.appendChild(iframe);
}
for (var i = 0; i < num_links; i++) {
document.getElementById('i_frame' + i).onload = function() {
var main = document.getElementById('i_frame' + i).contentDocument.getElementById('percentage').innerHTML;
var percentages = main.match(/(\d|\.)+\%/g);
console.log(percentages[0]);
};
}
该错误发生在行上:
var main = document.getElementById('i_frame' + i).contentDocument.getElementById('class_avg').innerHTML;"
错误:
Uncaught TypeError: Cannot read property 'contentDocument' of null
at HTMLIFrameElement.document.getElementById.onload