如何正确检查第一子节点是否隐藏并设置函数Bool

How to Properly Check if First Child is Hidden and Then Set Function Bool

本文关键字:隐藏 设置 函数 Bool 是否 子节点 何正确 检查      更新时间:2023-09-26

我正试图回答我最近的一个问题,我相信最好的答案涉及到一个函数偷看第一个子元素,然后设置一个bool在该函数之外的另一个函数使用。

回顾一下:我有一个GridView它的结构是这样的:

  • 组合

    • dept-header

      • (某人实体)
      • (某人实体)
      • (某人实体)
    • dept-header

      • (某人实体)
      • (某人实体)
      • (某人实体)
  • 组合

    • dept-header

      • (某人实体)
      • (某人实体)
      • (某人实体)
    • dept-header

      • (某人实体)
      • (某人实体)
      • (某人实体)

基本上,我希望当group-header被单击时,它隐藏所有下面的行,直到下一个group-header,如果它们不隐藏,否则显示它们。

我有代码和HTML设置在https://jsfiddle.net/dLp47mtd/1/,但问题的代码是不扩展/折叠是:

// Hide/Show Group's Data on Click
$(function() {
    $('.group-header').click(function() {
        // Assume first dept-header not visible
        var nextVisible = 0;
        // Check if the first dept-header is visible
        $(this).firstChild(function() {
            var el = this;
            // If visible, change our assumption
            if (el.style.display === '') {
                nextVisible = 1;
            }
        });
        // If visible, hide all sub-elements else show all sub-elements
        $(this).nextUntil('.group-header').each(function() {
            var el = this;    
            if (nextVisible === 1) {
                el.style.display = 'none';
            } else {
                el.style.display = '';
            }
        });
    });
});

如果您想显示和隐藏组下的所有行,而不需要记住已经切换了哪些部门,那么这对我来说很有效。

https://jsfiddle.net/dLp47mtd/5/

// Hide/Show Dept's Data on Click
$(function () {
    $('.dept-header').click(function () {
        $(this).nextUntil('.dept-header, .group-header').toggle();
    });
});
$(function () {
    $('.group-header').click(function () {
        var elm = $(this);
        if (elm.next().is(":visible")) {
            elm.nextUntil('.group-header').hide();
        } else {
            elm.nextUntil('.group-header').show();
        }
    });
});

Demo

$('.group-header').click(function() 
{
    $(this).nextAll().each(function()
    {
        if($(this).hasClass("group-header"))
            return false;
        if($(this).is(":visible"))
            $(this).hide();
        else
            $(this).show();
    });
});