getElementsByClassName 不起作用
我编写了一个 php 页面,将 mysql 数据库中的信息整齐地显示到表格中。我想使用 onLoad 事件处理程序隐藏空表行。
下面是一个示例表,其中包含在没有内容时隐藏 的代码。但我只能让它与不同的 ID 一起工作:
<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>
我想做的是使用 的类来实现相同的事情,同时只引用该类一次,而不是引用我想要删除的每个 ID,这甚至不适用于我的动态内容。我尝试使用此代码:
<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>
但它不起作用。它应该隐藏具有指定类的空 。如何使用类而不是 ID 隐藏空
?
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.
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>
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>
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几个问题:
getElementsByClassName()
。示例(未经测试):
请注意
getElementsByClassName()
不适用于 IE8(含)。更新:
或者,您可以为表提供一个 ID 并使用:
获取所有
td
元素。要隐藏父行,请使用元素的
parentNode
属性:There are several issues:
getElementsByClassName()
.Example (untested):
Note that
getElementsByClassName()
is not available up to and including IE8.Update:
Alternatively you can give the table an ID and use:
to get all
td
elements.To hide the parent row, use the
parentNode
property of the element:如果你想通过 ClassName 来做到这一点,你可以这样做:
If you want to do it by ClassName you could do: