2

我有以下 javascript/jquery-snippet:

var msg = (function() {
    var active = null;
    var toggleBox = function(parent) {
        if (active != null) {
            if (active.next().length) {
                active.slideUp("fast", function() {
                    active = active.next();
                    active.slideDown("fast");
                });
            } else hideBox();
        } else {
            parent.show();
            active = $(".myBox");
            active.slideDown("fast");
        }

    }
    var hideBox = function() {
        if (active != null) {
            active.slideUp("fast"); // doesn't work :(
            // hide parent, too... but it's not necessary here...
        }
    }
return {
    toggleBox : toggleBox,
    hideBox : hideBox
}
})();

以及以下几个html标签:

<div onclick="msg.toggleBox($('#parent'))">Show</div>
    <div id="parent" style="display: none;">
        <div class="myBox" style="display: none;">
            Message 1
            <div onclick="msg.toggleBox($('#parent'))">Next</div>
            <div onclick="msg.hideBox()">Hide</div>
    </div>
    <div class="myBox" style="display: none;">
        Message 2
        <div onclick="msg.hideBox()">Hide</div>
    </div>
</div>

现在...当我单击“显示”时,将显示第一个框,我可以关闭/隐藏该框。单击“下一步”,将显示第二个框。问题是,我无法隐藏第二个框。当我尝试使用时,alert(active.html())我总是得到活动对象的正确 html 代码。我也可以打电话hide(),第二个盒子会被隐藏,但根本没有slideUp()……为什么?我得到了一个有效的 jQuery 对象。

4

1 回答 1

0

尝试

var msg = (function() {
    var active = null;
    var toggleBox = function(parent) {
        if (active != null) {
            if (active.next().length) {
                active.slideUp("fast", function() {
                    active = active.next();
                    active.slideDown("fast");
                });
            } else 
                hideBox();
        } else {
            parent.show();
            active = $(".myBox").first(); //minor tweak here, if there is no active item activate the first myBox
            active.slideDown("fast");
        }

    }
    var hideBox = function() {
        if (active != null) {
            active.slideUp("fast"); // doesn't work :(
            // hide parent, too... but it's not necessary here...
        }
    }
    return {
        toggleBox : toggleBox,
        hideBox : hideBox
    }
})();

演示:小提琴

于 2013-05-31T14:19:34.403 回答