2013-02-21 41 views
0

我有這個代碼:這個功能爲什麼不起作用?

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

回答

1

當你運行:

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

在你自己的函數中,「frames」是在內部聲明的。 您可以嘗試刪除「var」關鍵字,使其成爲全局變量。

+0

我不會建議污染全局名稱空間作爲解決方案。請參閱http://stackoverflow.com/questions/39691/javascript-best-practices/39970#39970 – Gazler 2013-02-21 15:32:23

0

我認爲這個問題可能會在frames變量,它可能不是裏面的setInterval訪問。你可以試試這個

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