我有下面的代碼,它工作正常,但我覺得它很愚蠢,希望有一個更乾淨的「切換」功能或類似的,我可以使用但似乎是相關的只能看到 - 我想設置一個變量(以備後用)。jQuery切換排序順序並保存到變量
如果我想要一個應該用來對列進行排序的切換函數(並將值賦給變量),可以優化下面的這個嗎?
<table>
<thead>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>B</td>
<td>C</td>
<td>A</td>
</tr>
</tbody>
</table>
而jQuery的東西:
var column;
var order;
$('thead th').click(function() {
// Get the current column clicked
var thisColumn = $(this).text();
// Check if the column has changed
if(thisColumn == column) {
// column has not changed
if(order == "ascending") {
order = "descending";
} else {
order = "ascending";
}
} else {
// column has changed
column = thisColumn;
order = "descending";
}
// Replace text in DIV
$("div").text("column=["+column+"], order=["+order+"]");
// future code will use the sort order to get database
// stuff with Ajax
});
檢查的jsfiddle這裏的代碼,http://jsfiddle.net/Psz5K/
http://codereview.stackexchange.com/ – j08691
而不是一個全局變量,你可以使用數據屬性,順序必須是字母數字或數字0/1而不是? –