我有一个包含动态数量的iframe的页面。必须在iframes加载时调用window.print()(即有src)。
如何在纯JavaScript中优雅地处理这个问题而不是迂腐?
答案 0 :(得分:1)
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
}
答案 1 :(得分:0)
你可以做到
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);
}
这将迭代所有iframe,并返回true或false,表示是否所有iframe都定义了src
。
答案 2 :(得分:0)
不太确定这是否是你想要的,但也许有帮助:
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&#39; s $(document).ready
...