我正在尝试使用jQuery遍历一个HTML表并删除空行。页面是由ASP.NET驱动的,如果有一定的权限,表中的项将被隐藏。因此,我希望创建此脚本来删除空行,并消除仍然显示的其他项之间的空格。我似乎不能得到我目前必须运行的东西,我也不确定为什么。代码如下:
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
$(this).find('td').each(function () {
if ($(this).text().trim() == "") {
$(this).closest("tr").remove();
};
});
});
});
</script>
任何指导都将不胜感激。谢谢!
发布于 2011-03-31 23:08:00
您的代码似乎工作得很好。尝试单独运行以下命令,以了解我的意思:
<html>
<head>
<title>jQuery Tests</title>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
$(this).find('td').each(function () {
if ($(this).text().trim() == "") {
$(this).closest("tr").remove();
};
});
});
});
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td></td>
<td>testing</td>
</tr>
<tr>
<td>testing</td>
<td>testing</td>
</tr>
<tr>
<td>testing</td>
<td> </td>
</tr>
</table>
</body>
页面上可能还有其他冲突的东西吗?
发布于 2013-04-03 18:18:54
如果我们只有TD为空,而所有其他TD都已填充,则会导致问题
我正在更改代码以使其考虑到这一点
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
var totalTDs = $(this).find('td').length;
var emptyTDS = 0;
$(this).find('td').each(function () {
if ($(this).text().trim() == "") {
emptyTDS += 1;
};
});
if (emptyTDS == totalTDs) {
$(this).remove();
}
});
});
</script>
发布于 2011-03-31 23:06:05
试试这个:
var td = $(this).find('td:empty');
if ( td.length > 0 ) $(this).remove();
http://api.jquery.com/empty-selector/
也就是说,您确实希望在服务器端执行此操作。它在客户端看起来很丑陋,因为在触发文档就绪事件之前,您会看到空行将事情搞得一团糟。
https://stackoverflow.com/questions/5501908
复制相似问题