javascript JS:通过 getElementsByClassName 隐藏某些元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13367803/
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
JS: Making certain elements hidden via getElementsByClassName
提问by Kage the Klown
I'm trying to set up a script that sets invisible everything with a certain class name. This is an example of what I'm trying to call:
我正在尝试设置一个脚本,该脚本将具有特定类名的所有内容设置为不可见。这是我尝试调用的示例:
<script type="text/javascript">
function hideItems(){
document.getElementsByClassName('class1').style.visibility = "hidden";
}
</script>
The class names are on the dimensions of a table, similar to this example:
类名位于表的维度上,类似于此示例:
<table onclick="hideItems()" width="200" border="1">
<tr>
<td class="class1">1</td>
<td class="class2">2</td>
<td class="class3">3</td>
<td class="class1">1</td>
<td class="class2">2</td>
<td class="class3">3</td>
</tr>
<tr>
<td class="class3">3</td>
<td class="class1">1</td>
<td class="class2">2</td>
<td class="class3">3</td>
<td class="class1">1</td>
<td class="class2">2</td>
</tr>
</table>
In the end, there's going to be a three checkboxes, displaying the dimensions based on which of the three are selected. That part, I can do just fine, but calling the particular dimensions to become invisible is what I'm having an issue with currently.
最后,将有三个复选框,根据选择了三个复选框来显示维度。那部分,我可以做得很好,但是将特定维度称为不可见是我目前遇到的问题。
Thanks in advance for any kind of help.
在此先感谢您的任何帮助。
回答by Eli Gassert
getElementsByClassName
returns a collection. You can't collectively set properties unless you're using a framwork like jquery
getElementsByClassName
返回一个集合。除非您使用像这样的框架,否则您不能集体设置属性jquery
var elems = document.getElementsByClassName('class1');
for(var i = 0; i != elems.length; ++i)
{
elems[i].style.visibility = "hidden"; // hidden has to be a string
}