How can I simply make my HTML table 'dynamic&#

2019-09-11 05:47发布

问题:

I'm writing Multimarkdown from Perl to create an HTML table.

I wonder if there's a simple way to make the table dynamic , that is, allow the viewer sort it by clicking on a column header, or even filter records by entering a simple rule.

I do not really know HTML. I'm coding in Perl and only generate HTML (actually, Multimarkdown converted to HTML) to nicely output some data. I mention this since I'm sure there are various ways to create beautiful, dynamic tables, but I'm really looking for a simple one.

回答1:

The simple way is to use a toolkit/library that already supports such features.

(A quick google search for "sorting javascript table" turned up Table with sorting/filtering from JavaScript Toolbox, Sorting HTML Tables using JavaScript (more of example) and jQuery plugin: Tablesorter 2.0.)

AJAX is one mechanism that can be used to fetch data dynamically -- however, if all the data is already present in the table and/or the table doesn't need paging, then it's overkill. Both of these methods require that client-side JavaScript is enabled. (The non-client side alternative would be to post-back and have the server do the work and generate new HTML. But that's so Web one-point-oh :-)

CSS (Cascading Style Sheets) is just for applying styles such as colors, background image, fonts or borders, etc (CSS selectors can work based on CSS classes which are often supplied in the HTML element class attribute. The documentation is simply stating that some pre-defined CSS class names are dynamically added -- by the JavaScript -- and thus can be "selected" upon easily for styling - for example, turning the sorted column lime green). CSS itself, however, can't control the sorting or filtering.

Daxim suggested Stuart Langridge's sorttable which is discussed in the following SO question: how to do client side sorting using querystring in hyperlink associated with the table header using Perl? (Go upvote daxim there if this edit was useful :-)

Happy coding.



回答2:

Yahoo YUI's datatable control has built-in column sorting.

YUI has tons of js functions you can just call and use.



回答3:

I used the code below:

$sql= "select * from table";
$sth = $dbh->prepare($sql);
$sth->execute() or die "Cannot execute sth: $DBI::errstr";
my $fields = join(',', @{ $sth->{NAME} });
my @th = split(',',$fields);
print '<table><thead><tr>';
foreach(@th){
  print '<th>'.$_.'</th>';
}
print '</tr></thead><tbody>';
while (my @next_row_fields = $sth->fetchrow_array()) {
  print '<tr>';
  foreach(@next_row_fields){
    print '<td>'.$_.'</td>';
  }
  print '</tr>';
}
print '</tbody></table>';


回答4:

JQuery is a Javascript library that lets you do all sorts of neat front-end stuff, including table sorting. It's not bad to work with (it's sort of like php) and you don't have to know much about html/css (though that never hurts).

http://jquery.com/