【发布时间】:2021-01-03 13:07:05
【问题描述】:
我在排序 HTML 表格时遇到问题。标题是可点击的并且它们会排序,但是它不能正确地对表格进行排序。我正在使用 ACF Pro 和 FacetWP。该表使用 PHP 是动态的,需要它才能按字母数字排序。从理论上讲,这种排序算法应该可以工作,但我不明白为什么它不能正确排序。任何帮助将不胜感激。谢谢!
cPrev = -1; // global var saves the previous c, used to
// determine if the same column is clicked again
function sortBy(c) {
rows = document.getElementById("sortable").rows.length; // num of rows
columns = document.getElementById("sortable").rows[0].cells.length; // num of columns
arrTable = [...Array(rows)].map(e => Array(columns)); // create an empty 2d array
for (ro = 0; ro < rows; ro++) { // cycle through rows
for (co = 0; co < columns; co++) { // cycle through columns
// assign the value in each row-column to a 2d array by row-column
arrTable[ro][co] = document.getElementById("sortable").rows[ro].cells[co].innerHTML;
}
}
th = arrTable.shift(); // remove the header row from the array, and save it
if (c !== cPrev) { // different column is clicked, so sort by the new column
arrTable.sort(
function(a, b) {
if (a[c] === b[c]) {
return 0;
} else {
return (a[c] < b[c]) ? -1 : 1;
}
}
);
} else { // if the same column is clicked then reverse the array
arrTable.reverse();
}
cPrev = c; // save in previous c
arrTable.unshift(th); // put the header back in to the array
// cycle through rows-columns placing values from the array back into the html table
for (ro = 0; ro < rows; ro++) {
for (co = 0; co < columns; co++) {
document.getElementById("sortable").rows[ro].cells[co].innerHTML = arrTable[ro][co];
}
}
}
<body>
<div style="overflow-x:auto;">
<table id="sortable" style="width:100%;">
<thead>
<tr style="cursor:pointer">
<th align="left">Address</th>
<th onclick="sortBy(1)" align="left">City</th>
<th onclick="sortBy(2)" align="left">State</th>
<th onclick="sortBy(3)" align="left">Type</th>
<th onclick="sortBy(4)" align="right">Available SF</th>
</tr>
</thead>
<tbody id="table-body">
<?php while ( have_posts() ): the_post(); ?>
<tr>
<td align="left">
<a href="<?php the_permalink(); ?>">
<?php the_field('building_address'); ?>
</a>
</td>
<td align="left">
<a href="<?php the_permalink(); ?>">
<?php the_field('city'); ?>
</a>
</td>
<td align="left">
<a href="<?php the_permalink(); ?>">
<?php the_field('state'); ?>
</a>
</td>
<td align="left">
<?php echo get_the_term_list($post->ID, 'property_type', '', ', '); ?>
</td>
<td align="right">
<a href="<?php the_permalink(); ?>">
<?php the_field('max_available_size'); ?>
</a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</body>
【问题讨论】:
-
排序不正确是什么意思?尝试用
return (a[c]+'').localeCompare(b[c]);替换return (a[c] < b[c]) ? -1 : 1; -
为什么选择 php、ACF Pro 或 FacetWP?我用纯 JavaScript 构建了一个出色而简单的表格排序器。
-
我正在开发一个 WordPress 网站
标签: javascript php html sorting columnsorting