简体   繁体   English

单击链接时,Jquery显示div

[英]Jquery show div when link gets clicked

Im trying to show/hide a div using jquery when a link gets clicked. 我试图在点击链接时使用jquery显示/隐藏div。 I put this in my head section: 我把它放在我的头部:

<script type="text/javascript"> 
  $("#attach_box").click(function {
    $("#sec_box").show()
    });        
</script>

I have a link that looks like this: 我有一个看起来像这样的链接:

<a href="#" id="attach_box">+ Add a Postal Address (If Different)</a>

And a div that looks like this: 一个看起来像这样的div:

<div id="sec_box" style="display: none;">
Hello world!!               
</div>

This doesn't work and I can't figure out why. 这不起作用,我无法弄清楚为什么。 Any ideas? 有任何想法吗?

You need to attach the click handler in the document.ready in order to make sure that the DOM has been loaded by the browser and all the elements are available: 您需要在document.ready中附加click处理程序,以确保浏览器已加载DOM并且所有元素都可用:

<script type="text/javascript"> 
   $(function() {
       $('#attach_box').click(function() {
           $('#sec_box').show();
           return false;
       });        
   });
</script>

Also you forgot to put parenthesis () next to the anonymous function in the click handler. 此外,您忘记在click处理程序中的匿名函数旁边放置括号()

Chances are the DOM isnt fully loaded yet. 机会是DOM尚未满载。

   <script type="text/javascript"> 
      $(document).ready(function()
      {  
         $("#attach_box").click(function() {
         $("#sec_box").show()
         });  
       });      
   </script>

put that in your head and put your initialization code in there. 把它放在你的头脑中并将初始化代码放在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM