我的 jQuery 有点问题。我想让它扩展一个div元素的高度,但似乎无法舔它。我正在使用以下脚本:
<script>
$('.button').click(function(){
$('#footer_container').animate({height:'150px'}, 500);
});
</script>
其中“.button”是触发动画的超链接类:
“#footer_container”是应该从 75 像素扩展到 150 像素的 div。
我正在使用
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
在我的文档的头部。它是不是错误的附件(我将它用于页面上运行的其他几个脚本)?我缺少什么? I've posted the prototype on my test website .它是底部蓝色栏中的矩形按钮,上面写着:单击以查看我们的成员(member)资格。它应该扩展 div 以显示额外的内容,但什么都不做:-(
有人有什么想法吗?非常感谢!!
最佳答案
您的罪魁祸首是您在元素出现在 DOM 中之前注册了处理程序。所以最终你的 .button
没有获得附加的点击处理程序,因为该元素在脚本执行时尚不存在。
<div id="memberships">
<script>
$('.button').click(function(){
$('#footer_container').animate({height:'150px'}, 500);
});
</script>
<a href="#" class="button">Click to see our memberships.</a>
</div>
将它附加到文档就绪处理程序中始终是一个安全的选择。即 $(function(){...});
并将它放在页面上的任何位置或外部 js 文件中。因为只有当它所在的文档准备就绪并且元素可用时才会加载它。
所以你会这样做:
$(function(){
$('.button').click(function(e){
e.preventDefault(); //just prevent the default behavior of the hyperlink
$('#footer_container').animate({height:'150px'}, 500);
});
});
此外,将 html 与脚本混合通常是一种不好的做法。它很难维护并且会显示出不可预测的行为。
关于javascript - jQuery div 扩展高度不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928240/