【问题标题】:get previous selected list item index and compare to current获取先前选定的列表项索引并与当前比较
【发布时间】:2017-07-26 17:01:54
【问题描述】:

我有一个列表作为轮播的分页点。每个选定的项目都会添加一个选定的类,我可以轻松获取该列表项的索引。

我需要能够将当前选定的列表项索引与之前选定的列表项索引进行比较,以便确定是否需要向它们添加任何动画。

理想情况下,我希望能够做到以下几点

if(currentIndex > 3 && currentIndex > oldIndex)
{do stuff}

【问题讨论】:

  • 如何检索当前索引?
  • var currentIndex = $(this).index();
  • 将 oldIndex 初始化为 -1。做个检查;如果 oldIndex 为 -1,则设置 oldIndex = currentIndex,否则如果 currentIndex > oldIndex(在此处做一些事情......然后设置 oldIndex = currentIndex)。
  • 为什么不能只将前一个值存储在一个变量中,并在选择下一个项目时读取该变量的值?
  • 你能提供更多代码吗?比如你在哪里设置选定的类以及旧的选定列表项会发生什么?

标签: javascript jquery list indexing items


【解决方案1】:

创建一个将存储旧索引的变量。选择下一个项目后,使用该变量的值来执行您想要的内容。完成后,将新位置分配给变量。当用户再次选择时,这将是旧索引。

我不知道你的代码,所以希望你能理解:

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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多