2011-04-27 46 views
4

我有以下的功能,基本上使用的iframe的高度設置爲高度它的內容:jQuery的功能有時不運行

$("#MSOPageViewerWebPart_WebPartWPQ1").load(function() 
     { 
      var Height = document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').contentWindow.document.body.scrollHeight; 

      document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').height = Height; 
     }); 

絕大多數的時間預計將運行,但在奇怪的情況下,它會在它工作之前多次重新加載頁面。當然,試圖調試它是沒有用的,因爲它似乎總是碰到功能和工作。

任何人都知道爲什麼它不可能每次都工作?

+0

這是否發生在所有瀏覽器上? – Andre 2011-04-27 16:13:12

+0

只在IE8上測試,因爲這是所有用戶都會使用的。還有一些SharePoint的「細微差別」,我們決定專注於IE。 – anothershrubery 2011-04-27 16:13:52

+0

你試圖把它放在$(function {})? – alexl 2011-04-27 16:15:20

回答

0

試試這個:

$(function(){ 
$("#MSOPageViewerWebPart_WebPartWPQ1").load(function() 
     { 
setTimeout(function(){ 
      var Height = document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').contentWindow.document.body.scrollHeight; 

      document.getElementById('MSOPageViewerWebPart_WebPartWPQ1').height = Height; 
     }); 
},100); 
}); 
0

爲什麼使用 '的getElementById'。嘗試使用jQuery內建的選擇器機制:

jQuery("#MSOPageViewerWebPart_WebPartWPQ1").load(function() { 
    // not sure, if this row work's fine in every context, try: http://stackoverflow.com/questions/926916/how-to-get-the-bodys-content-of-an-iframe-in-javascript/11107977#11107977 
    var scrollHeight = jQuery(this).contentWindow.document.body.scrollHeight; 

    jQuery(this).height = scrollHeight; 
}); 
0

我遇到了同樣的問題。有時候沒有腳本運行。但是,我認爲這是一個連接問題。當我沒有連接到互聯網,並查看我的網站(瀏覽器使用其文件路徑,例如file:/// C:/Users/Alejandro/Dropbox/Prices/index.html)時,頁面需要相當長的時間加載時間(這很奇怪,因爲它是輕量級的),之後顯示內容但沒有任何腳本運行。

我想它在加載頁面時會延遲,因爲瀏覽器試圖下載jQuery源代碼。

所以,我會做的是包括一個jquery後備。 More info in xandercoded's answer

雖然如果你設置你的網站在線,這將是愚蠢的,因爲用戶已經需要互聯網連接下載你的網站(從而jQuery將被下載)。