这个功能为什么不起作用?

问题描述:

我有这个代码:这个功能为什么不起作用?

var frames = document.getElementsByTagName("iFrame"); 
var auto_resize_timer = window.setInterval("autoresize_frames()", 400); 
function autoresize_frames() { 
    for (var i = 0; i < frames.length; ++i) { 
     if (frames[i].contentWindow.document.body) { 
      var frames_size = frames[i].contentWindow.document.body.offsetHeight; 
      if (document.all && !window.opera) { 
       frames_size = frames[i].contentWindow.document.body.scrollHeight; 
      } 
      frames[i].style.height = frames_size + 'px'; 
     } 
    } 
} 

这是工作的罚款。

于是,我决定把它自己的模块中:

function autoResizeFrames() { 
    var frames = document.getElementsByTagName("iFrame"); 
    window.setInterval("autoresize_frames(frames)", 400); 
} 

function autoresize_frames(frames) { 

    for (var i = 0; i < frames.length; ++i) { 
     if (frames[i].contentWindow.document.body) { 
      var frames_size = frames[i].contentWindow.document.body.offsetHeight; 
      if (document.all && !window.opera) { 
       frames_size = frames[i].contentWindow.document.body.scrollHeight; 
      } 
      frames[i].style.height = frames_size + 'px'; 
     } 
    } 
} 

并运行它在页面像这样:

<script type="text/javascript"> 

    $(document).ready 
(
    function() { 
     autoResizeFrames(); 
    } 

    ); 

</script> 

但现在它不工作?任何想法为什么?

谢谢

+0

“不工作”究竟怎么了? – graphicdivine 2013-02-21 15:29:38

当你运行:

window.setInterval("autoresize_frames(frames)", 400); 

你基本上是eval荷兰国际集团代码窗口的上下文。使用setInterval时,应该传递对函数的引用而不是字符串。您可以了解为什么EVAL是坏Why is using the JavaScript eval function a bad idea?

通常你会用:

window.setInterval(autoresize_frames, 400); 

但是,如果你的函数有参数,那么你需要将它包装在一个函数。

下面的工作:

window.setInterval(function() { 
    autoresize_frames(frames); 
}, 400); 

在你自己的函数中,“frames”是在内部声明的。 您可以尝试删除“var”关键字,使其成为全局变量。

+0

我不会建议污染全局名称空间作为解决方案。请参阅http://stackoverflow.com/questions/39691/javascript-best-practices/39970#39970 – Gazler 2013-02-21 15:32:23

我认为这个问题可能会在frames变量,它可能不是里面的setInterval访问。你可以试试这个

function autoResizeFrames() { 
    window.setInterval(function(){ 
     autoresize_frames(document.getElementsByTagName("iFrame")) 
    }, 400); 
}