使用 Javascript 类显示/隐藏表格行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19797064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show/Hide Table Rows using Javascript classes
提问by user2957683
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. And IE and FireFox are only showing the first Hidden Row and not the others. I suspect this happens because I've made it work by triggering all IDs together. I think it would be better if I use Classes instead of IDs to indetify the hidden rows.
问题是我为每个人使用一个 ID,这很烦人,因为我想为每个父级和许多父级设置很多隐藏行,因此处理的 ID 太多了。IE 和 FireFox 只显示第一个隐藏行,而不显示其他行。我怀疑发生这种情况是因为我通过同时触发所有 ID 使其工作。我认为如果我使用类而不是 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 但无法得到它。
回答by Taylan Aydinli
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.
这是小提琴:link。
What you do is, instead of working with IDs, you work with classes. 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. So, I mark the product <tr>
s with class="cat1"
or class="cat2"
.
你所做的是,不是使用 ID,而是使用类。在您的代码示例中,有 Oranges 和 Apples。我把它们当作产品类别(因为我真的不知道你的目的是什么),有自己的 id。所以,我<tr>
用class="cat1"
或标记产品class="cat2"
。
I also mark the links with a simple .toggler
class. It's not good practice to have onclick
attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.
我还用一个简单的.toggler
类来标记链接。onclick
在元素本身上拥有属性不是一个好习惯。您应该使用 JavaScript 在页面加载时“绑定”事件。我使用 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
. In my code, I add a data-prod-cat
attribute to the toggler
links to specify which product rows they should control. (The reason for my using a data-*
attribute is explained here. You can Google 'html5 data attributes' for more information.)
使用这种格式,您将事件处理程序绑定到click
具有 class 的链接事件toggler
。在我的代码中,我data-prod-cat
向toggler
链接添加了一个属性,以指定它们应该控制哪些产品行。(此处data-*
解释了我使用属性的原因。您可以谷歌“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. I use $(this).attr('data-prod-cat')
this to access the data-prod-cat
attribute of the link the user clicks. I use the jQuery togglefunction, 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 deals with that. The toggle function does what it says and toggle
s the visibility of the specified element(s).
使用这段代码,我实际上是在尝试创建一个选择器,$('.cat1')
这样我就可以为特定的产品类别选择行,并更改它们的可见性。我使用$(this).attr('data-prod-cat')
它来访问data-prod-cat
用户单击的链接的属性。我使用 jQuery切换功能,这样我就不必if visible, then hide element, else make it visible
像在 JS 代码中那样编写逻辑。jQuery 处理这个问题。切换功能按照它所说toggle
的做,并确定指定元素的可见性。
I hope this was explanatory enough.
我希望这已经足够解释了。
回答by nnnnnn
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. Note that I've added <thead>
and <tbody>
to your markup to make it easy to hide data rows and ignore heading rows.
这大大简化了您的 html。请注意,我已将<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>
正文末尾的元素中,以便它在解析表后运行。
回答by spartikus
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
JQuery 10.1.2 有一个很好的显示和隐藏函数,可以封装您正在谈论的行为。这将使您不必编写新函数或跟踪 css 类。
$("tr1").show();
$("tr1").hide();
回答by Vijay Kumbhoje
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
只需showhiderow()
在单选按钮onClick
事件上调用函数
回答by Poornima
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 中进行了测试,并且工作正常。
回答by user1920925
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. ng-hide performs the same task but requires inverse condition.
一行在 rw.isExpanded == true 时可见,在 rw.isExpanded == false 时隐藏。ng-hide 执行相同的任务,但需要相反的条件。