2012-10-05 38 views
2

我有一个包含动态数量的iframe的页面。 window.print()必须在iframes加载时调用(即具有src)。检测页面中的所有iframe是否具有src

如何在纯JavaScript中轻松处理这些问题而不会变得迂腐?

+0

iframe是否全部在您的控制之下?或者他们中的一些不同的领域,你不能控制? – jfriend00

+0

它来自外部来源,不在我的控制之下。 – PHearst

回答

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 
} 
+0

重如果条件,但它是一种奇怪的问题,所以这是一个合理的解决方案。 – PHearst

+0

@kevin:有没有办法检查iframe是否有src ........... if(iframe_loaded){do_nothing ...} else {加载iframe src} – Hitesh

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); 
} 

这将在遍历所有的I帧和返回true或false就是否个个都定义一个src

+0

frames.reduce返回Fx 15中的错误? “错误:TypeError:frames.reduce不是函数” –

+0

显然不是,但它是Firefox 15.0.1。 –

+0

Durr,我需要先使用Array.prototype.slice。固定的 – saml

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的$(document).ready相同...

+0

谢谢,但为了支持IE,它得到了_kind_迂腐;-) – PHearst

+0

但是在一般情况下,它最好检查onload,因为我必须为每个iframe添加一些额外的加载时间,即使它具有src。 – PHearst

+0

这些也是我的想法。也许你应该考虑在这种情况下有点迂腐......) – Aletheios

相关问题