【问题标题】:jQuery Toggle modificationjQuery切换修改
【发布时间】:2011-02-13 02:42:03
【问题描述】:

我正在使用下面的 javascript (jQuery) 来切换打开两个 DIV。 DIV 可以很好地打开,一次打开一个,这就是我所追求的。但是,我还希望 DIV 在第二次单击时关闭,尽管我尽了最大努力,但还是没有发生!

Javascript:

$(document).ready(function() {
    $('.info_tab').click( function() {
        var currentID = $(this).next().attr("id");
        $('.toggle_info[id!=currentID]').hide(); /* the intention here is to hide anything that is not the current toggling DIV so as to close them as a new one is opened.  I thought this would leave the currently selected DIV uninterrupted to toggle closed (below), but it doesn't */
        $(this).next().toggle();
        return false;
        });
    });

HTML:

        <div class="info_tab">
            <h1>Person One</h1><br />
            <p>click for less info</p>
        </div>
        <div id="person_one_info" class="toggle_info">
            <p>More information about Philip Grover</p>
        </div>
        <div class="info_tab">
            <h1>Person Two</h1><br />
            <p>click for less info</p>
        </div>
        <div id="person_two_info class="toggle_info">
            <p>More information about Roy Lewis</p>
        </div>

如果需要更多信息,请提出,我很乐意编辑问题。

干杯,

丰富

【问题讨论】:

    标签: javascript jquery html toggle


    【解决方案1】:

    你有这个概念,但没有正确使用“currentID”。你需要记住它是一个变量,如果你想评估它就不能在另一个字符串中。

    话虽如此,试试这个:

    $('.toggle_info[id!='+currentID+']').hide();
    

    这使得变量在选择器中得到求值,然后将其传递给 jQuery 进行查找。

    不过,您似乎要达到手风琴效果。 jQuery UI 有 just such a control 供您使用(如果您有兴趣)。如果您要体验,请继续。 ;-)

    【讨论】:

    • 完美运行!我只是想体验一下——我的最后一口气是使用 jQuery 的手风琴,但我确信我自己可以做到!非常感谢:)
    • @richieahb:那么向你致敬。如果您愿意,这里有一个演示,只是为了确认。也让它滑动而不是仅仅隐藏/显示。 ;-) jsfiddle.net/3VuAK
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多