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.
这是一个示例表,其中包含在没有内容时隐藏 Here is a sample table with code that hides a 我想要做的是为 what i want to do is use a class for the 但它不起作用.它应该隐藏具有指定类的空 but it does not work. its supposed to hide the empty 有几个问题: 示例(未经测试): 请注意, 更新: 或者,您可以为表指定一个 ID 并使用: Alternatively you can give the table an ID and use: 获取所有 要隐藏父行,请使用元素的 To hide the parent row, use the 这篇关于getElementsByClassName 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 的代码.但我只能让它使用不同的 ID:
<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,这甚至不适用于我的动态内容.我尝试使用此代码:<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>
.我如何使用类而不是 ID 隐藏空的 <td>
s?
<td>
s that have the specified class. how do i hide empty <td>
s using classes, not IDs?推荐答案
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.var elements = document.getElementById('tableID').getElementsByTagName('td');
td
元素.parentNode
属性:parentNode
property of the element:elements[i].parentNode.style.display = "none";
登录
关闭