2013-07-28 25 views
-2

我有下面的代碼的問題:的document.ready不可達

<html> 
<head> 
    <link href='http://fonts.googleapis.com/css?family=PT+Sans:400italic' rel='stylesheet' type='text/css'> 
    <link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'> 
    <link href='http://fonts.googleapis.com/css?family=PT+Sans:700' rel='stylesheet' type='text/css'> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script> 
</head> 
<body> 
<input type = "button" value = "test" /> 
<script> 
function firstload() { 
    alert("start"); 
    $(document).ready(function() { 
     alert("foo"); 
    }); 
    alert("end"); 
} 
addEventListener('load', function() { 
    'use strict'; 
    setTimeout(firstload, 0); 
}, false); 
</script> 
</body> 
</html> 

當我做了一些workarround,我沒發現有什麼不對的代碼。

上面的代碼被保存爲php,但是當保存爲html時,甚至不會wor inking。

我從來沒有達到alert(「end」)語句,也從來沒有達到alert(「foo」)語句。

我該如何用$(docuemnt).ready編寫一些代碼。

+0

你需要把'$(文件).ready'功能'firstload外()'函數。如果你想等待所有的元素加載,你可以使用'$(window).load()'函數。 –

+0

爲什麼使用額外的事件偵聽器而不只是$(document).ready? – Iansen

回答

1

外就個人而言,我從來沒有使用'addEventListener',特別是在做一個onready函數時。

的最佳實踐,jQuery的,就是用這樣的:

$(function(){ 
    //insert code here 
}); 

//insert other functions out here 

這裏是你怎麼用。就緒做到這一點:

$(document).ready(function() { 
    //insert code here 
}); 

//insert other functions out here 

我不能告訴你爲什麼你的代碼沒沒有用,但我確信這會。

這裏是鏈接到jQuery的網站:http://api.jquery.com/ready/

2

你有沒有試過?

function firstload() { 
    alert("end"); 
} 
$(function(){ /* or $(document).ready(){ */ /* if you prefere */ 
    firstload(); 
}); 

CNC中

在執行準備功能至極內的文檔window.load其有點冗餘..,也警報「端」是的document.ready

+0

你有沒有試過_explaining_爲什麼OP的代碼不起作用,爲什麼這會解決它? –

+0

我想我有另一個問題。上述作品在localhost上,但不在託管網站上工作。 我已將Google API複製到我的託管網站,並且一切正常。 – Eitan

+0

您是否在Chrome/Firefox控制檯中看到任何錯誤?像jQuery文件的404錯誤? –