getElementsByClassName不起作用 [英] getElementsByClassName not working
问题描述
我编写了一个php页面,它将mysql数据库中的信息整齐地显示在表格中。我想用onLoad事件处理程序隐藏空表行。
I coded a php page that displays information from a mysql database neatly into tables. I would like to hide empty table rows with an onLoad event handler.
这是一个示例表,其代码隐藏< td>
什么时候没有内容。但我只能使用不同的ID:
Here is a sample table with code that hides a <td>
when it has no content. but i can only get it to work with different IDs:
<script type="text/javascript">
function hideTd(id){
if(document.getElementById(id).textContent == ''){
document.getElementById(id).style.display = 'none';
}
}
</script>
</head>
<body onload="hideTd('1');hideTd('2');hideTd('3');">
<table border="1">
<tr>
<td id="1">not empty</td>
</tr>
<tr>
<td id="2"></td>
</tr>
<tr>
<td id="3"></td>
</tr>
</table>
</body>
我想要做的是使用< td>的类。
实现相同的功能,同时只引用类一次,而不是引用我想删除的每个id,这对我的动态内容都不起作用。我尝试使用此代码:
what i want to do is use a class for the <td>
s to achieve the same thing while only referencing the class once, and not referencing every single id that I want to remove, which will not even work for my dynamic content. I tried using this code:
<script type="text/javascript">
function hideTd(){
if(document.getElementsByClassName().textContent == ''){
document.getElementsByClassName().style.display = 'none';
}
}
</script>
</head>
<body onload="hideTd('1');">
<table border="1">
<tr>
<td class="1">not empty</td>
</tr>
<tr>
<td class="1"></td>
</tr>
<tr>
<td class="1"></td>
</tr>
</table>
</body>
但它不起作用。它应该隐藏具有指定类的空< td>
。如何使用类而不是ID隐藏空< td>
?
but it does not work. its supposed to hide the empty <td>
s that have the specified class. how do i hide empty <td>
s using classes, not IDs?
推荐答案
有几个问题:
- 班级名称(和ID)是不允许以数字开头。
- 你必须通过一个class to
getElementsByClassName()
。 - 你必须迭代结果集。
示例(未经测试):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
请注意 getElementsByClassName()
不适用于IE8 。
更新:
或者,您可以为表格提供ID并使用:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
获取所有 td
元素。
要隐藏父行,请使用元素的 parentNode
属性:
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
这篇关于getElementsByClassName不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!