我一直在爲此奮鬥了幾天,當然原因和解決方案似乎事後很容易。 :)
原因:當所有的元素都寫到DOM jQuery是真的finnicky關於順序和時間
- jQuery的(文件)。就緒()運行。
- 我們使用AJAX來打印」 .media_container是到頁面
目前腳本運行時,頁面看起來是這樣的:
<html>
<head>
<script>
window.onload(){
loadContent(); //which uses ajax to inject php into the html
}
</script>
</head>
<body>
//empty
<script>
jQuery(document).ready(function(){
$('.media_container').someFunction();
});
</script>
</body>
</html>
$(document).ready() happens before window.onload()
因此,即使盡管jQuery腳本位於body
的末尾,但它在之前運行,loadContent()
腳本head
這是由window.onload()
觸發。事件
進一步澄清:序列
1. Browser reads html/php document, top down.
2. Browser reads the script in the `head` and waits for `window.onload()`
3. Simultaneously, it loads the `html` elements into the DOM.
4. It reaches the end of the document and reads and loads a jQuery script and waits for `jQuery(document).ready()'
5. Since it's already basically done with loading the DOM, the jQuery script runs <i>before</i> the window.onload() script runs.
解決方案:<img onload>
即使觸發document.ready()
,而不是window.onload()
的loadContent()
不起作用,因爲當它運行Ajax和用途php將元素插入HTML中,jQuery腳本已經運行。
因此,我做了兩兩件事,以加快代碼:
- 我對
document.ready()
- 跑
loadContent()
在每個AJAX/PHP拉結束,我添加具有visibility:hidden
和<img src='spaceholder.jpg' onload='attachFunctions()'>
一個media_container
,其中attachFunctions()在head
中運行的腳本文件中定義,並且問題已解決!
新代碼:
<html>
<head>
<script>
$(document).ready(function(){
loadContent(); //which uses ajax to inject php into the html
});
attachFunctions(){
$('.media_container').someFunction();
}
</script>
</head>
<body>
<div class='media_container'></div>
<div class='media_container'></div>
<div class='media_container'></div>
<div class='media_container' style='visibility:hidden'>
<img src='spaceholder.jpg' onload='attachFunctions()'>
</div>
</body>
</html>
你能提供的HTML? – Satpal
'.media_containers'或'.media_container' ??顯示你的html – mithunsatheesh
如果.media_container在iframe中,jquery不能訪問它。 –