Javascript 当链接被点击时,Jquery 显示 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3124537/
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
Jquery show div when link gets clicked
提问by Thomas
Im trying to show/hide a div using jquery when a link gets clicked. I put this in my head section:
当单击链接时,我尝试使用 jquery 显示/隐藏 div。我把它放在我的头部部分:
<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?
这不起作用,我不知道为什么。有任何想法吗?
回答by Darin Dimitrov
You need to attach the clickhandler in the document.readyin order to make sure that the DOM has been loaded by the browser and all the elements are available:
您需要在document.ready中附加点击处理程序,以确保浏览器已加载 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 clickhandler.
您还忘记()在click处理程序中的匿名函数旁边放置括号。
回答by Chris Kooken
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.
把它放在你的脑海里,然后把你的初始化代码放在那里。

