Javascript - 如何在找到课程之前切换所有下一个单曲

时间:2015-03-14 03:46:07

标签: javascript

我的下表默认隐藏了所有child行。

我想切换相应点击的root行下方的所有子行。也就是说,点击n旁边的.child .root行。我怎么能用纯Javascript做到这一点?



.hidden {
    display:none;
}

<table>
    <tr>
        <td><a href="#" onclick="func(this)">Root</a></td>
    </tr>
    <tr class="hidden">
        <td>Child 1</td>
    </tr>
    <tr class="hidden">
        <td>Child 2</td>
    </tr>
    <tr class="hidden">
        <td>Child 3</td>
    </tr>
    <tr class="hidden">
        <td>Child 4</td>
    </tr>
    <tr>
        <td><a href="#" onclick="func(this)">Root</a></td>
    </tr>
    <tr class="hidden">
        <td>Child 1</td>
    </tr>
    <tr class="hidden">
        <td>Child 2</td>
    </tr>
</table>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

如果,您想要做的是从单击后的所有行中删除hidden类名,直到找到未隐藏的行,然后您可以执行此操作:

function func(root) {
    var row = root.parentNode.parentNode;
    row = nextElement(row, "tr");
    while (row && row.className === "hidden") {
        row.className = "";
        row = nextElement(row, "tr");
    }

}

function nextElement(start, tag) {
    tag = tag.toUpperCase();
    start = start.nextSibling;
    while (start) {
        if (start.tagName === tag) {
            return start;
        } else {
            start = start.nextSibling;
        }
    }
    return start;
}

工作演示:http://jsfiddle.net/jfriend00/dvg6j9or/


这是另一个版本,它使用行数组并使用父搜索来查找表的正确级别:

function func(root) {
    var table = findParentTag(root, "table");
    var currentRow = findParentTag(root, "tr");
    var rows = Array.prototype.slice.call(table.querySelectorAll("tr"));
    var currentIndex = rows.indexOf(currentRow) + 1;
    // now traverse rows until you find one that is different than the starting row
    for (; currentIndex < rows.length; ++currentIndex) {
        if (rows[currentIndex].className.indexOf("hidden") !== -1) {
            rows[currentIndex].className = "";
        } else {
            break;
        }
    }

}

function findParentTag(start, tag) {
    tag = tag.toUpperCase();
    while (start && start.tagName !== tag) {
        start = start.parentNode;
    }
    return start;
}

工作演示:http://jsfiddle.net/jfriend00/hut56fLg/