使用jQuery删除表中的空行和列

Pet*_*son 4 javascript jquery dom html-table

假设我有一个这样的表:

+-----------+
| | | | | | |
|-+-+-+-+-+-|
| |a| |b| | |
|-+-+-+-+-+-|
| | | | | | |
|-+-+-+-+-+-|
| |c| |d| | |
|-+-+-+-+-+-|
| | | | | | |
+-----------+
Run Code Online (Sandbox Code Playgroud)

我想删除所有空的外部行和列.上面的例子将简化为:

+-----+
|a| |b|
|-+-+-|
| | | |
|-+-+-|
|c| |d|
+-----+
Run Code Online (Sandbox Code Playgroud)

我有一些工作代码,但它不是很优雅,更重要的是,速度太慢.我需要一个可以快速删除多达30个无关行和列的解决方案.

有没有一个快速和中途体面的方式来做到这一点?

Tom*_*lak 9

var $theTable = $("table#myTable"),
    lookAt    = ["tr:first-child", "tr:last-child", 
                 "td:first-child", "td:last-child"];

for (var i=0; i<lookAt.length; i++) {
  while ( $.trim($(lookAt[i], $theTable).text()) == "" ) {
    $(lookAt[i], $theTable).remove();
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:您可以使用它作为内循环,也许它更快一点:

for (var i=0; i<lookAt.length; i++) {
  while ( var $x = $(lookAt[i], $theTable), $.trim($x.text()) == "" ) {
    $x.remove();
  }
}
Run Code Online (Sandbox Code Playgroud)