我查看了十多个有关使用 onclick
、click
、bind("click", ...)
的问题、 on("click", ...)
等,但尚未找到我遇到的问题。
基本上它是一个可展开的 div,在不展开时会隐藏一些内容。我使用带有数据切换按钮的 Twitter Bootstrap collapse
类来展开/折叠内容本身,但我还需要修改容器 div 的 CSS 以增加高度,以便在视觉上,内容所在的盒子将拉伸(stretch)以容纳它。
这是我的脚本代码:
$(document).ready(function() {
$("#expand-button").bind('click', expandClick($));
document.getElementById("#expand-button").bind("click", expandClick($));
});
function expandClick($) {
$("#outer-container").animate({ "height": "350" }, 500);
$("#expand-button").html("^");
$("#expand-button").bind("click", collapseClick($));
};
function collapseClick($) {
$("#outer-container").animate({ "height": "50" }, 500);
$("#expand-button").html("V");
$("#expand-button").bind("click", expandClick($));
}
这个想法很简单,处理程序根据按钮的状态进出。实际发生的情况是,一旦我加载页面,expandClick 函数就会立即执行,这会引发容器上下弹跳的无限循环,尽管没有单击任何内容。
有什么想法吗?
另外,我认为它不相关,但 HTML 看起来像:
<div id="outer-container" class="container-fluid subsession-collapsed">
<div class="row-fluid" style="height: 50px">
<!-- OTHER STUFF... -->
<div class="span1" id="4">
<button id="expand-button" class="btn-success" data-toggle="collapse" data-target="#expandable">V</button>
</div>
</div>
<br /><br />
<div id="expandable" class="row-fluid collapse">
<div class="span12" style="padding: 0 20px">
<!-- CONTENT -->
</div>
</div>
</div>
编辑:
我曾经尝试寻找解决方案的一个主题是 this one ,但所有响应都给出了相同的结果。
最佳答案
该语句将expandClick
的结果指定为处理程序,即
$("#expand-button").bind('click', expandClick($));
应该是
$("#expand-button").bind('click', function() { expandClick($) });
另一个问题是您从 expandClick
和 collapseClick
添加更多点击处理程序,但从未删除它们
这就是我将您的代码重写为的内容,我不知道您为什么要传递 $
$(document).ready(function() {
// Cache your variables instead of looking them up every time
var expandButton = $("#expand-button"),
outerContainer = $("#outer-container");
function expandClick() {
outerContainer.animate({ "height": "350" }, 500);
expandButton.html("^");
// Remove the previous handler
expandButton.off('click', expandClick );
// Bind the new handler
expandButton.bind("click", collapseClick);
};
function collapseClick() {
outerContainer.animate({ "height": "50" }, 500);
expandButton.html("V");
// Remove the previous handler
expandButton.off('click', collapseClick);
// Bind the new handler
expandButton.bind("click", expandClick);
}
expandButton.bind('click', expandClick);
// What is this????
//document.getElementById("#expand-button").bind("click", expandClick($));
});
关于JQuery onclick 在单击元素之前不断触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13145725/