2016-03-08 84 views
0

我有一個JavaScript功能,它不會觸發頁面刷新。當我從另一個頁面導航到頁面時,它起作用,但如果刷新頁面,則失敗。我的javascript功能不會觸發頁面刷新

所有此功能確實將頁面中的一個元素的高度分配給另一個元素的高度(如果它們都存在)。

jQuery(document).ready(function ($) { 
    if ($(".Video_Pane iframe").length && $(".Image_Pane img").length) { 
     $(".Video_Pane iframe").height($(".Image_Pane img").height()) 
    } 
} 

任何想法?控制檯不顯示任何有關此錯誤

+0

您可以設置一個[最小,完整且可驗證](http://stackoverflow.com/help/mcve)示例的[fiddle](https://jsfiddle.net)嗎? – clinei

回答

4

img的存在並不意味着它已被加載(,因此您可以讀取它的高度)。 刷新通常會使圖像的緩存版本無效,因此必須重新加載

嘗試使用load事件,而不是ready

jQuery(window).load(function ($) { 
    if ($(".Video_Pane iframe").length && $(".Image_Pane img").length) { 
     $(".Video_Pane iframe").height($(".Image_Pane img").height()) 
    } 
}) 
+0

這對我來說確實看起來很完美,但是我假設不是'加載'窗口,它不能被改變來檢查'$(「。Image_Pane img」)''的加載'嗎? – Jai

+1

@jai它不可靠,因爲如果圖像被緩存,處理程序可能不會被觸發。請參閱https://api.jquery.com/load-event/以及有關「***注意事項與圖像一起使用時的加載事件***」的部分。「 –

+1

太棒了!錯過了這些警告。再次感謝您的提醒。 – Jai

0

你必須在你的代碼語法錯誤(窗口對象上)。 在最後的}之後有一個);失蹤。

我只是想它和它的工作對我來說是這樣的:

jQuery(document).ready(function ($) { 
    console.log("Hello"); 
}); 
+0

不!看到其他** upvoted **答案。 – Jai

+0

我看到了upvoted的答案。但他無論如何都忘記了'';''在他的代碼中。或者他可能忘了複製它。 –

0

你缺少一個支架。

jQuery(document).on('ready',function() { 
    if ($(".Video_Pane iframe").length && $(".Image_Pane img").length) { 
     $(".Video_Pane iframe").height($(".Image_Pane img").height()) 
    } 
}); 

我也會使用.on('ready')而不是.ready。

+0

不!看到其他** upvoted **答案。 – Jai