[英]how to sort default td inside table alphabetically with javascript jquery
I am using this table and script for sorting alphabetically the data inside the td
: 我正在使用此表和脚本按字母顺序对
td
的数据进行排序:
<button type=button>Sort Options</button>
<table class="table-data">
<tr>
<td class="filename">C</td>
</tr>
<tr>
<td class="filename">A</td>
</tr>
<tr>
<td class="filename">D</td>
</tr>
<tr>
<td class="filename">B</td>
</tr>
</table>
And the jquery: 和jQuery:
$('button').click(function() {
var options = $('table.table-data td');
var arr = options.map(function(_, o) {
return {
t: $(o).text(),
v: o.value
};
}).get();
arr.sort(function(o1, o2) {
return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
});
options.each(function(i, o) {
console.log(i);
o.value = arr[i].v;
$(o).text(arr[i].t);
});
});
Now the sorting happens when clicking on the button. 现在,单击按钮即可进行排序。 How can I make the sorting default when loading the page?
加载页面时如何使排序默认? (without clicking button)
(不单击按钮)
The same code you have as an event handler can be used as a named function. 与事件处理程序相同的代码可以用作命名函数。 Then if you want it to run on page load, just call it on page load!
然后,如果您希望它在页面加载时运行,只需在页面加载时调用它即可!
// Have it a named function instead of an event handler function sortTds(){ var options = $('table.table-data td'); var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get(); arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; }); options.each(function(i, o) { console.log(i); o.value = arr[i].v; $(o).text(arr[i].t); }); } // Call the function on page load sortTds();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="table-data"> <tr> <td class="filename">C</td> </tr> <tr> <td class="filename">A</td> </tr> <tr> <td class="filename">D</td> </tr> <tr> <td class="filename">B</td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.