我想在點擊特定按鈕時對錶的列值進行排序。我首先想弄清楚如何用預先定義的值對錶格進行排序(我在表格中包含了2行和實際值)。其次,在完成表格中的預定義值排序後。我希望能夠添加一個「創建行」按鈕,它可以隨機生成任何值甚至字母。而且,點擊按鈕後,值將被排序。 我的代碼壞了,我不知道爲什麼!使用沒有插件的jquery對錶的列進行排序
我被卡住了,我找不到多少幫助!在此先感謝你們!
//add row function
$(document).ready(function() {
$("#add_row").click(function() {
event.preventDefault();
var new1 = $("<tr><td>6</td><td>1</td><td><input id ='dr' class='btn btn-danger' type ='button' value= 'delete'></td></tr>").on('click', function() {
$(this).find('td').toggleClass('highlighted')
});
$('#myTable').append(new1);
});
//delete function
$('#myTable').on('click', '#dr', function() {
$(this).parent().parent().remove();
});
//sort function
$('#sort1,#sort2').on('click', function() {
var n1 = $(this).index();
console.log(n1);
var n2 = $('#myTable').find('tbody >tr:has(td)').get();
console.log(n2);
n1 += 1;
n2.sort(function(a, b) {
var vA = $(a).children(':nth-child(' + n1 + ')').text();
var vB = $(b).children(':nth-child(' + n1 + ')').text();
if (vA < vB) {
return -1;
} else if (vA > vB) {
return 1;
} else {
return 0
};
});
$.each(n2, function(index, row) {
$('tbody').append(row);
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>create table</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
table,
td {
border: 1px solid black;
}
.highlighted {
background-color: yellow;
}
</style>
</head>
<body>
<div class="container">
<p>Click the buttons to create and delete row(s) for the table.</p>
<table id="myTable" class="table" style="width: 80%">
<tbody>
<tr>
<td>Name<button type="button" id="sort1" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></td>
<td>Value<button type="button" id="sort2" class="btn btn-default btn-xs pull-right glyphicon glyphicon-triangle-bottom"></button></td>
<td>Deletable</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
<br>
<button type="button" id="add_row" class="btn btn-primary">Create row</button>
</div>
</body>
看到這個【答案】(https://stackoverflow.com/questions/664802/jquery-sorting-a-table-without-the-plugin)它工作正常。 –
@Haze,我之前看到過這個答案,但我認爲它太複雜了,它主要關注javascript而不是jquery。但感謝您的輸入,雖然! –