https://jsfiddle.net/danvim/2xh4LLgr/3/
You need to remember $this
changes in different function scope.
Do this to set the target:
var $this = $(this)
Updated code:
$(".link-sort-list").on("click",function(e){
var $this = $(this); //<--
var $list = $('#sort-list');
var $productList = $('div.product-box',$list);
$productList.sort(function(a, b){
var keyA = $(a).attr("price");
var keyB = $(b).attr("price");
if($this.hasClass('asc')){ //<--
console.log("asc");
return (parseInt(keyA) > parseInt(keyB)) ? 1 : 0;
} else {
console.log("desc");
return (parseInt(keyA) < parseInt(keyB)) ? 1 : 0;
}
});
$.each($productList, function(index, row){
$list.append(row);
});
e.preventDefault();
});
Final Solution
But I would recommend putting the checking of $this
outside the sort
method. Also, you wouldn't need the shorthand-if, just return the Boolean value will do.
So I would simplify it like so: https://jsfiddle.net/danvim/2xh4LLgr/5/
This will run quicker because the checking for .asc
only happens once whereas your original function will check once for every item to be compared.
$(".link-sort-list").on("click",function(e){
var $this = $(this);
var $list = $('#sort-list');
var $productList = $('div.product-box',$list);
var order = $this.hasClass('asc');
console.log(order);
$productList.sort(function(a, b){
var keyA = $(a).attr("price");
var keyB = $(b).attr("price");
return order ? (parseInt(keyA) > parseInt(keyB)) : (parseInt(keyA) < parseInt(keyB));
});
$.each($productList, function(index, row){
$list.append(row);
});
e.preventDefault();
});