Jquery 切换不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3708086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:56:43  来源:igfitidea点击:

Jquery toggle not working

jqueryhtmlcsshidetoggle

提问by DonJuma

i am trying to get jquery to hide this div and for some reason it is not working what am i doing wrong

我试图让 jquery 隐藏这个 div 并且由于某种原因它不起作用我做错了什么

http://stat-me.com/jq.html

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>

回答by Rob Grant

You need to:

你需要:

  1. Use document.ready
  2. Select the anchor underneaththe #one div, not the div itself
  1. 使用document.ready
  2. 选择#one div下方的锚点,而不是 div 本身

So it should be:

所以应该是:

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

回答by Lewis

Your not wrapping your javascript in $(document).ready(function(){})etc do jQuery is trying to find an element that doesn't exist yet!

您没有将您的 javascript 包装在$(document).ready(function(){})etc do jQuery 中试图找到一个尚不存在的元素!

回答by Govind Totla

I am having the same situation while using ajax and applied this solution. Write javascript:void(0); instead of a '#' in href value. this prevents you to add '#' in url. use .live() when using in ajax mode. in .toggle(), pass argument as effect like 'Drop', 'slide' etc, more at http://jqueryui.com/toggle/.

我在使用 ajax 时遇到了同样的情况并应用了这个解决方案。编写 javascript:void(0); 而不是 href 值中的“#”。这可以防止您在 url 中添加“#”。在 ajax 模式下使用时使用 .live() 。在 .toggle() 中,将参数作为“Drop”、“slide”等效果传递,更多信息请访问http://jqueryui.com/toggle/

$(document).ready(function(){
        $('#one a').live('click', function(){
            $('#hideme').toggle('Drop');
            return false;
         });
     });

Applying return false; at last preventing me to reload the page.

应用 return false; 最后阻止我重新加载页面。

Answered just for knowledge.

回答只是为了知识。