我有一个包含动态数量的iframe的页面。 window.print()必须在iframes加载时调用(即具有src)。检测页面中的所有iframe是否具有src
如何在纯JavaScript中轻松处理这些问题而不会变得迂腐?
我有一个包含动态数量的iframe的页面。 window.print()必须在iframes加载时调用(即具有src)。检测页面中的所有iframe是否具有src
如何在纯JavaScript中轻松处理这些问题而不会变得迂腐?
function getLoadedFrames() {
var frames = document.getElementsByTagName('iframe'), // Get all iframes
loadedFrames = [], i;
for (i = 0; i < frames.length; i++) {
/*
If iframe has a src attribute, that attribute has a value AND
that value is not equal to the current window location (leaving src
blank seems to return the current location instead of empty string)
then add the frame to the loadedFrames array.
*/
if (frames[ i ].src && frames[ i ].src.length > 0 && frames[ i ].src !== window.location.href) {
loadedFrames.push(frames[ i ]);
}
}
return loadedFrames; // An array of your 'loaded' frames
}
你可以做
function areAllIframesLoaded() {
var frames = document.getElementsByTagName('iframe')
return Array.prototype.slice.call(frames).reduce(function(p, c) {
return p && c.src && c.src.length > 0 && c.src !== window.location.href
}, true);
}
这将在遍历所有的I帧和返回true或false就是否个个都定义一个src
。
frames.reduce返回Fx 15中的错误? “错误:TypeError:frames.reduce不是函数” –
显然不是,但它是Firefox 15.0.1。 –
Durr,我需要先使用Array.prototype.slice。固定的 – saml
不太清楚,如果这就是你想要的,但也许它可以帮助:
window.addEventListener("DOMContentLoaded", function(){
// Get all iframes as soon as DOM has loaded
var iframes = document.getElementsByTagName("iframe");
for (var i = 0, l = iframes.length; i < l; ++i) {
// Add event handler to every iframe
iframes[i].onload = function(){
// Execute window.print() when iframe has loaded
window.print();
};
}
});
这个工作没有检查src
属性,因为如果一个iframe
没有src
,该onload
事件绝不会被解雇。
请注意,这不会在IE中工作;请参见SO上的this answer,与jQuery的$(document).ready
相同...
iframe是否全部在您的控制之下?或者他们中的一些不同的领域,你不能控制? – jfriend00
它来自外部来源,不在我的控制之下。 – PHearst