简体   繁体   English

基于层次结构的Javascript折叠和扩展表行

[英]Javascript-Collapsing and expanding table rows based on hierarchy

I have the following table generated by a cgi script: 我有一个cgi脚本生成的下表:

<table>
<tr id='vfipbb'><td>col 1,0</td><td>col 1,1</td></tr>
<tr id='vfipbb.alipbb'><td>col 2,0</td><td>col 2,1</td></tr>
<tr id='vfipbb.esipbb'><td>col 3,0</td><td>col 3,1</td></tr>
<tr id='vfipbb.esipbb.esipbb_madrid'><td>col 4,0</td><td>col 4,1</td></tr>
<tr id='vfipbb.esipbb.esipbb_barcelona'><td>col 5,0</td><td>col 5,1</td></tr>
</table> 

This is just a sample of what it would look like, but the important bit to note is the id. 这只是其外观的一个示例,但需要注意的重要一点是id。

when the webpage first loads all rows are collapsed except for the root context (vfipbb). 当网页首次加载时,除根上下文(vfipbb)之外的所有行均折叠。 I want to enable functionality when the root context is clicked it will expand all child rows listed under this, for example (alipbb), (esipbb) and if one of the child rows is clicked it will expand all grandchildren rows, for example (esipbb_madrid) (esipbb_barcelona). 我想在单击根上下文时启用功能,它将展开在此之下列出的所有子行,例如(alipbb),(esipbb),如果单击子行之一,它将展开所有子孙行,例如(esipbb_madrid )(esipbb_barcelona)。

Is there any efficient way of doing this in javascript based on ID? 在基于ID的javascript中,有任何有效的方法吗? Any pointer in the right direction would be greatly welcome! 任何朝着正确方向的指针都将受到欢迎!

Not a working code, but something to get you started 不是有效的代码,但可以帮助您入门

// add click handlers  to all tr   
var tr0 = document.getElementsByTagName("tr");
for (var i = 0; i < tr0.length; i++) {
   tr0[i].addEventListener("click", openChild);
}


function openChild() {

    var id = this.id;

   //regex that matches a string beginning with 
   //the id followed by dot and some other words
   var regex = new RegExp("^" + id + ".[a-z_]+$", "g");

   var tr1 = document.getElementsByTagName("tr");

   //browse through the tr(s)
   for (var i = 0; i < tr1.length; i++) {

       //Learn regex test function!
       if (regex.test(tr1[i].id)) //if a match found
        //display children
        document.getElementById(tr1[i].id).style.visibility = "visible";
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM