【问题标题】:Selecting parent div and not every div with the same name with jQuery使用 jQuery 选择父 div 而不是每个具有相同名称的 div
【发布时间】:2014-05-03 02:31:53
【问题描述】:

我的问题是,当我点击一个带有“触发器”类的 div 时,每个 div“组”都会打开,但只有父 div 应该打开,我该怎么做?

代码

// global variables
var nav           = $('.group'),
    navHeight     = nav.height()+15,
    items         = $('.group .item .trigger'),
    itemsSub      = items.next('.toggle_container'),
    itemsSubOpen  = false,
    speed         = 400;
// global functions
var navOpen = function (thisSubmenu) {
    itemsSubOpen = true;
    // get height
    thisSubmenu.css('height', 'auto');
    var thisHeight = thisSubmenu.height();
    thisSubmenu
        .css('height', '0')
        .animate({height: thisHeight }, speed)
        .addClass('open');

    nav.animate({height: thisHeight + navHeight }, speed);
};
var navClose = function () {
    itemsSubOpen = false;
    items.next('.open')
        .animate({height: 0}, speed)
        .removeClass('open');
    nav.animate({height: navHeight-15 }, speed);
};
// prepare css
itemsSub.css('display', 'block');
itemsSub.css('height', '0');
// click event
items.click(function(event) {
    // set local variables
    var thisItem = $(this),
        thisSubmenu = thisItem.next('.toggle_container');
    // conditional click event handling
    if ( itemsSubOpen  ) {
        if ( thisSubmenu.hasClass('open') ) {
            // only close
            navClose();
        } else {
            // close old, than open new
            navClose();
            setTimeout(function() {
                navOpen(thisSubmenu);
            }, speed);
        }
    } else {
        // only open
        navOpen(thisSubmenu);
    }
    // prevent default
    event.preventDefault();
});

我以这个小提琴为例: http://jsfiddle.net/kfcgg/15/ 也许你们中的一个可以帮助我解决这个问题。

谢谢

【问题讨论】:

    标签: jquery class parent


    【解决方案1】:

    正确的做法是只引用父 div!

    $(this).closest('.group')

    将仅引用父“组”类。我希望这是有用的!

    【讨论】:

    • 我在变量声明时更改了它,但它不起作用:jsfiddle.net/kfcgg/16
    • 尝试在函数中插入全局变量,看看它是如何工作的。它们不应该是全局的,因为它们的价值取决于您点击的位置!
    • 我会努力做点什么的!
    • 那太棒了。 :)
    • 我看到你只有两个带有类组的 div。当我单击上部项目时,在您的小提琴上,下面的文本显示。当我单击下部项目时,它们下方的文本会显示,而上部文本会隐藏。这里有什么问题以及您希望它如何反应?!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2011-01-02
    相关资源
    最近更新 更多