javascript Toggle 仅显示和隐藏某些表行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8195960/
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
Toggle Show And Hide Only Some Table Rows
提问by ONDEV
I am trying to show/hide (via a toggle mechanism) only certain rows in my table. I have gotten somewhat close, code is below. What I was reading about in other questions regarding this is the use of style id's and I have tried that but it fails for me. So that is why I used 'hide=yes' and pass that into the toggle function.
我正在尝试仅显示/隐藏(通过切换机制)表中的某些行。我已经有点接近了,代码如下。我在与此相关的其他问题中读到的是样式 ID 的使用,我已经尝试过,但对我来说失败了。所以这就是为什么我使用 'hide=yes' 并将其传递给切换函数的原因。
This is going to be a table with a couple of hundred entries that when I click toggle can be reduce down to less than 30 on any given day.
这将是一个包含数百个条目的表格,当我单击切换时,在任何一天都可以减少到少于 30 个条目。
Is there a better way to do this?
有一个更好的方法吗?
<html>
<head>
<script>
function toggle(thisname) {
tr=document.getElementsByTagName('tr')
for (i=0;i<tr.length;i++){
if (tr[i].getAttribute(thisname)){
if ( tr[i].style.display=='none' ){
tr[i].style.display = '';
}
else {
tr[i].style.display = 'none';
}
}
}
}
</script>
</head>
<body>
<span onClick="toggle('hide');">TOGGLE</span><br /><br />
<table>
<tr ><td >display this row 1</td></tr>
<tr hide=yes ><td>hide this row 1</td></tr>
<tr><td>display this row 2</td></tr>
<tr hide=yes ><td>hide this row 2</td></tr>
<tr hide=yes ><td>hide this row 3</td></tr>
<tr><td>display this row 3</td></tr>
<tr><td>display this row 4</td></tr>
<tr><td>display this row 5</td></tr>
<tr><td>display this row 6</td></tr>
<tr hide=yes ><td>hide this row 4</td></tr>
<tr hide=yes ><td>hide this row 5</td></tr>
<tr><td>display this row 7</td></tr>
<tr hide=yes ><td>hide this row 6</td></tr>
<tr hide=yes ><td>hide this row 7</td></tr>
</table>
</body>
</html>
采纳答案by david
Your approach seems ok, i suggest you declare variables tr
and i
你的方法似乎没问题,我建议你声明变量tr
和i
alternately you could use class
instead
交替你可以使用class
,而不是
<span onclick="toggle('yes');">
if (tr[i].className == thisname){
<tr class=yes>