各列の上にボタンがあるソート可能なテーブルがあります。ボタンをクリックすると、列が昇順と降順でソートされます。これが発生するたびに、th クラスが現在の状態を表すように変更されます。
$('th.sorting').on('click', 'span', function() {
alert("sorting");
$("span#i").html('');
jQuery("span#i", this).html(' <i class=\"icon-chevron-up\"></i>');
});
$('th.sorting_asc').on('click', 'span', function() {
alert("sorting_asc");
$("span#i").html('');
jQuery("span#i", this).html(' <i class=\"icon-chevron-down\"></i>');
});
$('th.sorting_desc').on('click', 'span', function() {
alert("sorting_desc");
$("span#i").html('');
jQuery("span#i", this).html(' <i class=\"icon-chevron-up\"></i>');
});
上記の関数を適用しようとしているコードの例を次に示します。
<th class="sorting"><span>Device<span id="i"></span></span></th>
私が今抱えている問題は、ボタンをクリックしたときに、上記の関数が th クラスが変更されたことを認識していないことです。列を並べ替えるとクラスが実際に変更され、データが適切に並べ替えられることを確認しました。
例として、列の 1 つが並べ替えられた列として読み込まれるため、sorting_asc などのマークが付けられます。別の列の並べ替えボタンをクリックすると、他のすべての列が .sorting になり、最近クリックした列は .sorting になります。 sorting_asc ...しかし、どういうわけか元の列をクリックしても(クラスが.sortingの場合)、「sorting_asc」というアラートが引き続き表示されます
私はそれを修正しました:
$("th > span").click(function() {
var th = $(this).parent("th");
if($(th).hasClass("sorting")) {
$("span#i").html('');
jQuery("span#i", this).html(' <i class=\"icon-chevron-up\"></i>');
}
if($(th).hasClass("sorting_asc")) {
$("span#i").html('');
jQuery("span#i", this).html(' <i class=\"icon-chevron-down\"></i>');
}
if($(th).hasClass("sorting_desc")) {
$("span#i").html('');
jQuery("span#i", this).html(' <i class=\"icon-chevron-up\"></i>');
}
});