<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready({
$('#sh').click(function(){
$('#container').show();
});
});
</script>
<style type="text/css">
#container {
width:350px;
height:350px;
border:1px solid #000000;
display:none;
}
</style>
</head>
<body>
<div id="container">
<p>paragraph 1</p>
</div>
<div>
<a href="#" id="sh">show</a>
</div>
</body>
</html>点击链接根本不会触发.show()!我做错了什么??更新:我尝试了$(文档).ready({...这没什么用!
发布于 2011-03-01 22:10:05
请记住,只有在文档加载完成后才能加载脚本:
$(function(){
/* Scripts here will run only
after the document has loaded */
});此外,在使用链接触发操作时,请务必对链接进行prevent the default behavior:
$(function(){
$("#sh").click(function(e){
e.preventDefault();
$("#container").show();
});
});有了这些更改,代码就可以正常工作了:http://jsfiddle.net/apsje/
发布于 2011-03-01 22:06:27
将您的jquery代码添加到
$(document).ready(function() {
...
});发布于 2011-03-01 22:06:57
使用以下命令:
因为如果您在调用真正的HTML之前调用脚本,那么您引用的元素还不存在。
$(document).ready( function() {
$('#sh').click(function(){
$('#container').show();
})通过在$(document)上使用ready事件,您可以确保DOM已完全加载并准备好与之交互。
https://stackoverflow.com/questions/5155533
复制相似问题