Jquery切换不起作用

10
我正在尝试使用jQuery隐藏这个div,但是不知道为什么它没有起作用。我做错了什么? http://stat-me.com/jq.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#one{
    border:3px solid #00F;
    width:50%;
}
#hideme{
    border:3px solid #00F;
    width:50%;
    display:none;
}
</style>

<script type="text/javascript" src="../_root/js/jquery/jquery-1.4.2.js"></script>

<script language="javascript" type="text/javascript">



$("#one").click(function () {
$("#hideme").toggle();
});

</script>

</head>

<body>

<div id="one">
<a href="#">hello</a>
</div>

<div id="hideme">
hi
</div>


</body>
</html>
3个回答

19

你需要做以下两件事:

  1. 使用 document.ready
  2. 选择 #one div 下面的锚点,而不是选择 div 本身

所以代码应该如下所示:

$(document).ready(function() {
  $("#one a").click(function() {
    $("#hideme").toggle();
  });
});

2
我遇到的这两个陷阱很多次 :) - Rob Grant

2

你没有将你的JavaScript代码包装在$(document).ready(function(){})等中,因此jQuery试图查找尚不存在的元素!


1
我在使用ajax时遇到了相同的情况,并采用了以下解决方法:将href值中的'#'替换为javascript:void(0);,以防止在url中添加'#'。在ajax模式下使用.live()。在.toggle()中,将效果作为参数传递,如'Drop'、'slide'等,更多信息请参见http://jqueryui.com/toggle/
$(document).ready(function(){
        $('#one a').live('click', function(){
            $('#hideme').toggle('Drop');
            return false;
         });
     });

在最后应用return false;可以防止页面重新加载。

仅供参考。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接