我有这个用于排序html元素的javascript。
SortingElements = function () {
var $this = $(this);
var order = "desc";
var lastClicked = null;
var list = null;
var sorting = null;
var init = function() {
var prevClicked = lastClicked;
sorting = $this.attr("data-sort");
if (prevClicked == sorting)
order = (order == "desc") ? "asc" : "desc";
lastClicked = sorting;
list = $('.sorting-list'), lis = $('.sort-item'), liHeight = lis[0].offsetHeight;
$(list).css('height', list.outerHeight());
tinysort('.sorting-list .sort-item', { selector: 'span[data-sorting="' + sorting + '"]', order: order }).forEach(function (elm, i) {
$(elm).fadeOut(i * 175);
$(elm).fadeIn(i * 175);
});
}
init();
}
使用$('.sort-selector-item').click(SortingElements);
调用此脚本,这是用于对f.x进行排序的锚列表。按名称,公司等。
<ul class="no-list list-inline list-unstyled sort-selector margin-bottom-30">
<li><a href="#" class="sort-selector-item" data-sort="name">Navn</a></li>
<li><a href="#" class="sort-selector-item" data-sort="company">Virksomhed</a></li>
<li><a href="#" class="sort-selector-item" data-sort="position">Stilling</a></li>
</ul>
我的问题是prevClicked变量。它应该获取前一个被点击项目的值,这样如果我再次单击同一个项目而不点击另一个项目,它可以对升序和降序排序进行排序,即如果我点击&#34; name&#34;它将按降序排序,如果我点击&#34; name&#34;它会再次升序。
简而言之,如果它包含与排序var相同的值,它应该按升序/降序排序
但问题是它总是null
,可能是因为var prevClicked = lastClicked;
答案 0 :(得分:1)
问题是lastClicked
和order
在函数调用之间不会持续存在。
使它们闭合(这可能是你init
的意图)应该有所帮助:
SortingElements = (function()
{
var order = "desc";
var lastClicked = null;
return function() // This function "becomes" SortingElements
{
var $this = $(this);
var list = null;
var sorting = null;
var prevClicked = lastClicked;
sorting = $this.attr("data-sort");
if (prevClicked == sorting)
order = (order == "desc") ? "asc" : "desc";
lastClicked = sorting;
list = $('.sorting-list'), lis = $('.sort-item'), liHeight = lis[0].offsetHeight;
$(list).css('height', list.outerHeight());
tinysort('.sorting-list .sort-item',
{
selector: 'span[data-sorting="' + sorting + '"]',
order: order
}).forEach(function (elm, i)
{
$(elm).fadeOut(i * 175);
$(elm).fadeIn(i * 175);
});
};
})();