获取上一个选定的列表项目索引并与当前比较
问题描述:
我有一个列表作为轮播的分页点。每个选定的项目添加一个选定的类,我可以很容易地获得该列表项目的索引。获取上一个选定的列表项目索引并与当前比较
我需要能够比较当前选择的列表项目索引与先前选择的列表项目索引,以便我可以确定是否需要向他们添加任何动画。
理想我想在一个位置做如下
if(currentIndex > 3 && currentIndex > oldIndex)
{do stuff}
答
创建将存储旧索引的变量。当选择下一个项目时,使用该变量的值来做你想要的。完成后,将新位置分配给变量。当用户再次选择时,这将是旧索引。
我不知道你的代码,所以我希望你明白:
var oldIndex = -1; // -1 indicates that the user hasn't yet selected any item
$('.all-the-items').click(function() {
var currentIndex = $(this).index();
if (oldIndex === -1) {
// the user has selected for the first time
} else {
// oldIndex holds the old index, currentIndex holds the current index
// do stuff with oldIndex and currentIndex
if(currentIndex > 3 && currentIndex > oldIndex) {
// ...
}
}
oldIndex = currentIndex; // set the old index to the current index
});
你如何检索当前的指数? – PeterMader
var currentIndex = $(this).index(); – user1464853
将oldIndex初始化为-1。做一个检查;如果oldIndex为-1,则设置oldIndex = currentIndex,否则,如果currentIndex> oldIndex(在此处做东西......然后设置oldIndex = currentIndex)。 –