jQuery在2个项目之间切换并关闭另一个项目

时间:2013-09-09 14:51:28

标签: javascript jquery html

我有2个列表项,当单击一个时,内部div被切换为打开状态。但问题是,当两者都被点击时,它们都保持开放状态。我想要它做的是当一个被点击时另一个将被关闭。

的jQuery

$('.register, .signin').click(function(e){
    e.preventDefault();
    var userclass = $(this).attr('class');
    $('.'+userclass+'-panel').toggle();
});

HTML

<ul class="user-status">
    <li><a class="register" href="#">Register</a>
        <div class="register-panel tooltip" style="display: none;">
            <form action="" method="post">
                <input type="email" name="email" id="email" placeholder="email"><div class="usernamecheck"></div>
                <input type="password" name="password" id="password" placeholder="password">
                <input type="submit" name="register" value="Register" disabled="disabled"><div class="userstatus"></div>
            </form>
        </div><!-- /register -->
    </li>
    <li><a class="signin" href="#">Sign In</a>
        <div class="signin-panel tooltip" style="display: none;">
            <form action="" method="post">
                <input type="email" name="email" placeholder="email"><div class="usernamecheck"></div>
                <input type="password" name="password" placeholder="password">
                <input type="submit" name="signin" value="Sign In"><div class="userstatus"></div>
            </form>
        </div><!-- /register -->
    </li>
</ul>

1 个答案:

答案 0 :(得分:2)

只需添加$('.tooltip').not('.'+userclass+'-panel').hide();

$('.register, .signin').click(function (e) {
    e.preventDefault();
    var userclass = $(this).attr('class');
    $('.' + userclass + '-panel').toggle();
    $('.tooltip').not('.' + userclass + '-panel').hide();
});

<强> jsFiddle example

这将隐藏未选中的表单。