Tôi cần bắt chước nhấp chuột vào "Tên" td sau khi vẽ bảng, vì vậy có vẻ như sắp xếp theo tên là mặc định.Bắt chước nhấp chuột
var link = "https://jsonplaceholder.typicode.com/users";
var usersData = [];
$(".buttonLoad").click(function() {
$(".buttonLoad").remove();
$.getJSON(link, function (data) {
usersData = data;
// Table draw
for(var i = 0; i < usersData.length; i++){
$("#users").append("<tr><td>" + usersData[i].id + "</td>" + "<td>" + usersData[i].name + "</td>"
+ "<td>" + usersData[i].username + "</td>" + "<td>" + usersData[i].email + "</td>"
+ "<td>" + usersData[i].address.street + "</td>" + "<td>" + usersData[i].address.suite + "</td>"
+ "<td>" + usersData[i].address.city + "</td>" + "<td>" + usersData[i].address.zipcode + "</td>"
+ "<td>" + usersData[i].address.geo.lat + "</td>"
+ "<td>" + usersData[i].phone + "</td>"
+ "<td>" + usersData[i].website + "</td>" + "<td>" + usersData[i].company.name + "</td>"
+ "<td>" + usersData[i].company.catchPhrase + "</td>" + "<td>" + usersData[i].company.bs + "</td></tr>")
}
});
$("table").removeClass("hide");
$('th.sort').click(function(){
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc;
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() }
});
.hide{
display: none;
}
button{
margin: 3px;
}
table {
width: 100%;
margin: auto;
margin: 3px;
}
table th {
font-weight: bold;
}
table th, table td {
padding: 3px;
border: 1px solid #000;
}
thead th{
font: bold italic 100% sans-serif;
background-color: #f7e1b5;
}
.sort{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<button class="buttonLoad">Load data</button>
<table id="users" border="1" class="hide">
<thead>
<tr>
<th>ID</th>
<th class="sort" id="defaultSort">Name</th>
<th class="sort">Username</th>
<th class="sort">Email</th>
<th class="sort">Street</th>
<th>Suite</th>
<th>City</th>
<th>Zipcode</th>
<th>Geo</th>
<th>Phone</th>
<th>Website</th>
<th class="sort">CompanyName</th>
<th>CatchPhrase</th>
<th>bs</th>
</tr>
</thead>
</table>
Những điều như .trigger("click")
hoặc element.click()
không làm việc ở tất cả.
tại sao không chỉ sắp xếp dữ liệu bạn nhận được qua json trước khi tạo bảng của bạn? – zerohero
Isnt 'nó chỉ vì trang không được tải xong .trigger (' click ') và .click() doesnt work? thử một cái gì đó như 'setTimeout (function() {$ ('# defaultSort'). click();}, 500);' Oh và giống như zerohero nói, tại sao không chỉ bắt đầu với nó được sắp xếp? ... –