问题
Been searching for answers but finding none. I have a code that displays a table pulled from a server-side genqueuesearch.php based on a parameter "rg1". Each row has a column called Queue with an "rg1" string in it. The table has several columns but my challenge is displaying only 4 columns. Here is my AJAX code:
<html>
<head>
<script language="Javascript">
function View(){
...
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("datatable").innerHTML=xmlhttp.responseText;
}
}
var parameters = "search="+"rg1";
xmlhttp.open("POST", "http://drcsblr0165/genqueuesearch.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}
</script>
</head>
<body onload="View()">
<div id="datatable" align="center"></div>
</body>
</html>
Tried getElementsbyTagName but I don't know the tag names for the columns I would like. Does this require saving the table to a text file first? I appreciate all your help and please ask if I'm not clear.
回答1:
Since you can't alter what the server is giving you, then we are restricted to solving this with JavaScript only. I do suggest you use jQuery because it'll make things much simpler for you.
jQuery utilizes CSS selector pattern for finding elements in the DOM. You can leverage it to select which columns in the table you'd like to hide. You can even select specific columns even if you don't know the name of them.
Say, you get back a table like this from the server and you've put it inside your <div id="datatable">
:
<div id="datatable" align="center">
<table>
<tr>
<td>dataRow1Col1</td>
<td>dataRow1Col2</td>
<td>dataRow1Col3</td>
<td>dataRow1Col4</td>
</tr>
<tr>
<td>dataRow2Col1</td>
<td>dataRow2Col2</td>
<td>dataRow2Col3</td>
<td>dataRow2Col4</td>
</tr>
<tr>
<td>dataRow3Col1</td>
<td>dataRow3Col2</td>
<td>dataRow3Col3</td>
<td>dataRow3Col4</td>
</tr>
<tr>
<td>dataRow4Col1</td>
<td>dataRow4Col2</td>
<td>dataRow4Col3</td>
<td>dataRow4Col4</td>
</tr>
</table>
</div>
For example, using the :nth-child
selector doesn't require you to know the class name, $('#datatable td:nth-child(3)').hide();
will select the 3rd column and hide it. (see example: http://jsfiddle.net/Cjsua/)
You may find more suitable selectors on the jQuery documentation: http://api.jquery.com/category/selectors/
The .hide()
function simply hides the elements matched.
来源:https://stackoverflow.com/questions/16802510/display-only-certain-columns-in-a-table