我刚刚开始使用jQuery并希望使用$(document).ready()来动态生成一些HTML加载页面的时间。它工作正常,当我使用内嵌的JavaScript代码,这样的(这个例子明显简化,但它表明了问题的行为):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#container").html("<p>Hello world</p>");
});
</script>
<title>Test</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
但是,如果我链接到外部JavaScript文件,并替换内嵌的JavaScript与这样的:
$(document).ready(start());
其中用于启动的代码是
function start(){
$("#container").html("<p>Hello world</p>");
}
没有任何反应。我在外部start()函数中放置了一个警告框,它弹出正常,所以函数内的代码正在执行。控制台也不会显示任何错误。不过,如果我更换
$("#container").html("<p>Hello world</p>");
与
document.getElementById("container").innerHTML = "<p>Hello world</p>";
控制台提供了一个错误,说的document.getElementById( “容器”)为空。
我真的很感激,如果有人能指出我在这个正确的方向。
啊,打我+1 – 2012-01-18 04:33:59
它的工作!非常感谢 :) – 2012-01-18 07:10:46