简体   繁体   English

使用Javascript类显示/隐藏表行

[英]Show/Hide Table Rows using Javascript classes

I have a table that kind of expands and collapses, but it's getting too messy to use it and IE and Firefox are not working properly with it. 我有一个扩展和折叠的表,但使用它太乱了,IE和Firefox无法正常使用它。

So, here's the JavaScript code: 那么,这是JavaScript代码:

  function toggle_it(itemID){ 
      // Toggle visibility between none and '' 
      if ((document.getElementById(itemID).style.display == 'none')) { 
            document.getElementById(itemID).style.display = '' 
            event.preventDefault()
      } else { 
            document.getElementById(itemID).style.display = 'none'; 
            event.preventDefault()
      }    
  } 

And a Sample HTML: 和一个示例HTML:

<table>
    <tr>
        <td>Product</td>
        <td>Price</td>
        <td>Destination</td>
        <td>Updated on</td>
    </tr>
    <tr>
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#" id="toggle" onClick="toggle_it('tr1');toggle_it('tr2')">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr id="tr1" style="display:none">
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr id="tr2" style="display:none">
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td>Apples</td>
        <td>100</td>
        <td><a href="#" id="toggle" onClick="toggle_it('tr3');toggle_it('tr4')">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr id="tr3" style="display:none">
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr id="tr4" style="display:none">
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
</table>

The problem is that I use one ID for each and every and that's very annoying because I want to have a lot of hidden rows for each parent and a lot of parents, so it would be too many IDs to handle. 问题是我每个人都使用一个ID而且这非常烦人,因为我想为每个父母和很多父母都有很多隐藏的行,所以要处理的ID太多了。 And IE and FireFox are only showing the first Hidden Row and not the others. IE和FireFox只显示第一个隐藏行而不显示其他隐藏行。 I suspect this happens because I've made it work by triggering all IDs together. 我怀疑这是因为我通过一起触发所有ID来使其工作。 I think it would be better if I use Classes instead of IDs to indetify the hidden rows. 我认为如果我使用Classes而不是ID来隐藏隐藏的行会更好。

I'm really new to all of this so please try and explaining it in any kind of simply way. 我对这一切都很陌生,所以请尝试以任何一种简单的方式解释它。 Also I've tried jQuery but wasn't able to get it. 我也试过jQuery但是无法得到它。

It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. 很难弄清楚你试图用这个样本做什么,但你实际上正在考虑使用类。 I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this. 我已经创建了一个JSFiddle来帮助演示一个稍微好一点的方法(我希望)。

Here's the fiddle: link . 这是小提琴: 链接

What you do is, instead of working with IDs, you work with classes. 你所做的不是使用ID,而是使用类。 In your code sample, there are Oranges and Apples. 在您的代码示例中,有橘子和苹果。 I treat them as product categories (as I don't really know what your purpose is), with their own ids. 我把它们视为产品类别(因为我真的不知道你的目的是什么),用它们自己的ID。 So, I mark the product <tr> s with class="cat1" or class="cat2" . 所以,我用class="cat1"class="cat2"标记产品<tr> s。

I also mark the links with a simple .toggler class. 我还用一个简单的.toggler类来标记链接。 It's not good practice to have onclick attributes on elements themselves. 在元素本身上使用onclick属性并不是一种好习惯。 You should 'bind' the events on page load using JavaScript. 您应该使用JavaScript在页面加载上“绑定”事件。 I do this using jQuery. 我使用jQuery做到这一点。

$(".toggler").click(function(e){
    // you handle the event here
});

With this format, you are binding an event handler to the click event of links with class toggler . 使用此格式,您将事件处理程序绑定到具有类toggler的链接的click事件。 In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. 在我的代码中,我向toggler链接添加了一个data-prod-cat属性,以指定它们应该控制哪些产品行。 (The reason for my using a data-* attribute is explained here . You can Google 'html5 data attributes' for more information.) (我在这里解释使用data-*属性的原因。您可以使用Google的'html5数据属性'获取更多信息。)

In the event handler, I do this: 在事件处理程序中,我这样做:

$('.cat'+$(this).attr('data-prod-cat')).toggle();

With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. 有了这段代码,我实际上是想创建一个像$('.cat1')这样的选择器,这样我就可以为特定的产品类别选择行,并改变它们的可见性。 I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. 我使用$(this).attr('data-prod-cat')来访问用户点击的链接的data-prod-cat属性。 I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. 我使用jQuery 切换功能,这样我就不必编写像是if visible, then hide element, else make it visible逻辑if visible, then hide element, else make it visible就像在JS代码中那样if visible, then hide element, else make it visible jQuery deals with that. jQuery处理它。 The toggle function does what it says and toggle s the visibility of the specified element(s). 切换功能执行它所说的内容并toggle指定元素的可见性。

I hope this was explanatory enough. 我希望这足够解释。

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes: 那么一种方法是将一个类放在“父”行上并删除所有id和内联onclick属性:

<table id="products">
    <thead>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Destination</th>
        <th>Updated on</th>
    </tr>
    </thead>
    <tbody>
    <tr class="parent">
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    ...etc.
    </tbody>
</table>

And then have some CSS that hides all non-parents: 然后有一些隐藏所有非父母的CSS:

tbody tr {
    display : none;          // default is hidden
}
tr.parent {
    display : table-row;     // parents are shown
}
tr.open {
    display : table-row;     // class to be given to "open" child rows
}

That greatly simplifies your html. 这大大简化了你的HTML。 Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows. 请注意,我已将<thead><tbody>到标记中,以便轻松隐藏数据行并忽略标题行。

With jQuery you can then simply do this: 使用jQuery,您可以简单地执行此操作:

// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
    // prevent default behaviour
    e.preventDefault();
    // find all the following TR elements up to the next "parent"
    // and toggle their "open" class
    $(this).closest("tr").nextUntil(".parent").toggleClass("open");
});

Demo: http://jsfiddle.net/CBLWS/1/ 演示: http//jsfiddle.net/CBLWS/1/

Or, to implement something like that in plain JavaScript, perhaps something like the following: 或者,在纯JavaScript中实现类似的东西,可能类似于以下内容:

document.getElementById("products").addEventListener("click", function(e) {
    // if clicked item is an anchor
    if (e.target.tagName === "A") {
        e.preventDefault();
        // get reference to anchor's parent TR
        var row = e.target.parentNode.parentNode;
        // loop through all of the following TRs until the next parent is found
        while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
            toggle_it(row);
    }
});

function nextTr(row) {
    // find next sibling that is an element (skip text nodes, etc.)
    while ((row = row.nextSibling) && row.nodeType != 1);
    return row;
}

function toggle_it(item){ 
     if (/\bopen\b/.test(item.className))       // if item already has the class
         item.className = item.className.replace(/\bopen\b/," "); // remove it
     else                                       // otherwise
         item.className += " open";             // add it
}

Demo: http://jsfiddle.net/CBLWS/ 演示: http//jsfiddle.net/CBLWS/

Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed. 无论哪种方式,将JavaScript放在正文末尾的<script>元素中,以便在解析表之后运行它。

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. JQuery 10.1.2有一个很好的show和hide函数,它们封装了你所谈论的行为。 This would save you having to write a new function or keep track of css classes. 这将节省您必须编写新函数或跟踪css类。

$("tr1").show();

$("tr1").hide();

w3cSchool link to JQuery show and hide w3cSchool链接到JQuery show和hide

event.preventDefault()

Doesn't work in all browsers. 不适用于所有浏览器。 Instead you could return false in OnClick event. 相反,您可以在OnClick事件中返回false。

onClick="toggle_it('tr1');toggle_it('tr2'); return false;">

Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine. 不确定这是不是最好的方法,但我在IE,FF和Chrome中测试过它的工作正常。

Below is my Script which show/hide table row with id "agencyrow". 下面是我的脚本,显示/隐藏id为“agencyrow”的表格行。

<script type="text/javascript">

                        function showhiderow() {
                            if (document.getElementById("<%=RadioButton1.ClientID %>").checked == true) {

                                document.getElementById("agencyrow").style.display = '';
                            } else {

                                document.getElementById("agencyrow").style.display = 'none';
                            }


                        }
    </script> 

Just call function showhiderow() upon radiobutton onClick event 只需在radiobutton onClick事件上调用函数showhiderow()

AngularJS directives ng-show, ng-hide allows to display and hide a row: AngularJS指令ng-show,ng-hide允许显示和隐藏行:

   <tr ng-show="rw.isExpanded">
   </tr>

A row will be visible when rw.isExpanded == true and hidden when rw.isExpanded == false. 当rw.isExpanded == true时会显示一行,当rw.isExpanded == false时会隐藏。 ng-hide performs the same task but requires inverse condition. ng-hide执行相同的任务但需要反向条件。

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

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