在单击元素之前,JQuery onclick不断触发

msh*_*t12 2 jquery twitter-bootstrap

我已经看了十多问题有关使用onclick,click,bind("click", ...),on("click", ...),等,还没有发现我有这个问题.

基本上它是一个可扩展的div,在不扩展时会隐藏一些内容.我正在使用collapse带有数据切换按钮的Twitter Bootstrap 类来扩展/折叠内容本身,但我还需要修改容器div的CSS以增加高度,以便在视觉上,内容所在的框将拉伸包含它.

这是我的脚本代码:

$(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($));
}
Run Code Online (Sandbox Code Playgroud)

这个想法很简单,处理程序根据按钮的状态旋转进出.实际发生的是,只要我加载页面,就会立即执行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>
Run Code Online (Sandbox Code Playgroud)

编辑:

我曾经尝试过找到解决方案的一个SO主题就是这个,但是所有的响应都给出了相同的结果.

Jua*_*des 5

此语句将结果分配expandClick为处理程序,即

$("#expand-button").bind('click', expandClick($));
Run Code Online (Sandbox Code Playgroud)

应该

$("#expand-button").bind('click', function() { expandClick($) });
Run Code Online (Sandbox Code Playgroud)

另一个问题是你从中添加了更多的点击处理程序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($));
});
Run Code Online (Sandbox Code Playgroud)