如何修改JavaScript实现页面加载时表格按指定列排序
页面加载时自动按第一列A-Z排序的修改方法
操作步骤:
- 打开你的
sortable-table.js代码,找到SortableTable类里的constructor函数(就是开头写着constructor(tableNode) {的那段代码)。 - 定位到函数内处理
optionCheckbox的代码块结束位置,也就是这段代码的末尾:if (this.optionCheckbox) { this.optionCheckbox.addEventListener( 'change', this.handleOptionChange.bind(this) ); if (this.optionCheckbox.checked) { this.tableNode.classList.add('show-unsorted-icon'); } } - 在上述位置后插入以下代码:
// 自动按第一列(Products)A-Z升序排序 const firstColumnIndex = 0; const firstHeader = this.columnHeaders[firstColumnIndex]; if (firstHeader.querySelector('button')) { firstHeader.setAttribute('aria-sort', 'ascending'); this.sortColumn(firstColumnIndex, 'ascending', firstHeader.classList.contains('num')); } - 保存代码,刷新页面即可看到表格加载时自动按第一列A-Z排序。
说明:
这段修改完全复用原代码的排序逻辑,同时保留了辅助技术所需的aria-sort属性,不会破坏原有的无障碍功能。代码会自动识别第一列为文本列,按字符串A-Z规则完成排序。
内容的提问来源于stack exchange,提问作者Cole B
相关产品推荐
相关产品推荐

