1

由于单击按钮时的空间问题,我正在尝试扩展内部 div。当用户点击一个按钮时,我想隐藏它的兄弟姐妹和父母的兄弟姐妹,直到指定的 id。如何使用 jquery 在 javascript 中执行此操作?

下面是一个例子:

大教堂:

<div id="p">
    <div id="p1-1">
        <div id="c1-1-1">
            <button id="expand"></button>
        </div>
        <div id="c1-1-2">
        </div>
    </div>
    <div id="p1-2">
        <div id="c1-2-1">
        </div>
    </div>
    <div id="p1-3">
        <div id="c1-3-1">
        </div>
    </div>
</div>

结果Dom:

<div id="p">
    <div id="p1-1">
        <div id="c1-1-1">
            <button id="expand"></button>
        </div>      
    </div>  
</div>
4

4 回答 4

2

Find the elements you want to keep visible using parentsUntil(), loop through them using each(), then hide their siblings().

$(button).click(function(){
    var elementsToKeep = $(this).parentsUntil('#stop_element_id');
    elementsToKeep.each(function(){
        $(this).siblings().hide();
    });
});

Not enough rep to post link to siblings().

于 2013-05-13T19:38:48.393 回答
1

'while-until' 循环应该可以解决问题:

var str_stop_id = "p",
    $el = $(this).parent();
while ($el.attr('id') !== str_stop_id) {
    $el = $el.siblings().hide().end().parent();
}

http://jsfiddle.net/mblase75/Wc2Pf/

于 2013-05-13T19:05:53.660 回答
1

如果我正确理解了这个问题:

$("#expand").on("click", function () {
    // Toggle text
    var text = $(this).text() == "Expand" ? "Collapse" : "Expand";
    $(this).text(text);
    // Toggle proximal element state
    $(this).parent().siblings().toggle();
    $(this).parent().parent().siblings().toggle();
});

看这个活生生的例子

于 2013-05-13T19:05:47.973 回答
0

这工作正常:

$(button).click(function(){
    var elementsToKeep = $(this).parentsUntil('#stop_element_id');
    elementsToKeep.each(function(){
        $(this).siblings().hide();
    });
});
于 2016-04-01T10:01:02.667 回答