admin管理员组

文章数量:1313105

Suppose I have a table like this:

+-----------+
| | | | | | |
|-+-+-+-+-+-|
| |a| |b| | |
|-+-+-+-+-+-|
| | | | | | |
|-+-+-+-+-+-|
| |c| |d| | |
|-+-+-+-+-+-|
| | | | | | |
+-----------+

I want to remove all of the outside rows and columns that are empty. The above example will be reduced to this:

+-----+
|a| |b|
|-+-+-|
| | | |
|-+-+-|
|c| |d|
+-----+

I have some working code, but it is not very elegant and, more importantly, prohibitively slow. I need a solution that can remove up to 30 extraneous rows and columns quickly.

Is there a fast and halfway-decent way to do this?

Suppose I have a table like this:

+-----------+
| | | | | | |
|-+-+-+-+-+-|
| |a| |b| | |
|-+-+-+-+-+-|
| | | | | | |
|-+-+-+-+-+-|
| |c| |d| | |
|-+-+-+-+-+-|
| | | | | | |
+-----------+

I want to remove all of the outside rows and columns that are empty. The above example will be reduced to this:

+-----+
|a| |b|
|-+-+-|
| | | |
|-+-+-|
|c| |d|
+-----+

I have some working code, but it is not very elegant and, more importantly, prohibitively slow. I need a solution that can remove up to 30 extraneous rows and columns quickly.

Is there a fast and halfway-decent way to do this?

Share Improve this question edited Dec 21, 2016 at 10:00 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 20, 2011 at 5:44 Peter OlsonPeter Olson 143k49 gold badges208 silver badges249 bronze badges 2
  • you want empty rows gone too so why is an empty row there in the desired result figure.. – Rafay Commented Dec 20, 2011 at 5:50
  • @3nigma I only want the outside empty rows and columns removed. Empty rows and columns in between content is desired. – Peter Olson Commented Dec 20, 2011 at 5:53
Add a ment  | 

1 Answer 1

Reset to default 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();
  }
}

EDIT: You could use this as the inner loop, maybe it's a little faster:

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

本文标签: javascriptRemove empty rows and columns in a table with jQueryStack Overflow