Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:在列表中查找特定的前一个元素并添加类_Javascript_Jquery_Algorithm - Fatal编程技术网

Javascript:在列表中查找特定的前一个元素并添加类

Javascript:在列表中查找特定的前一个元素并添加类,javascript,jquery,algorithm,Javascript,Jquery,Algorithm,我有一张这样的清单 在每个.list项中都有一个html按钮: <div class="list"> <button>.list</button> </div> 当我单击该按钮时,我希望上一个.list项具有.active类,如下所示: 使用jquery非常简单,我已经做到了,它的工作非常好: $('.list button').on('click', function() { $(this).closest(

我有一张这样的清单

在每个.list项中都有一个html按钮:

<div class="list">
<button>.list</button>
</div>
当我单击该按钮时,我希望上一个.list项具有.active类,如下所示:

使用jquery非常简单,我已经做到了,它的工作非常好:

$('.list button').on('click', function() {
    $(this).closest('.list').prev('.list').addClass('active');
});
但是我有一些具体的案例: 有时列表项可以隐藏,而具有隐藏类的列表不能包含。活动类:

或者更复杂。您必须逐一查看每个项目,并将活动类放在没有隐藏类的第一个项目上:

我在没有隐藏类的情况下对项目进行了力学分析,但我恐怕我走错了方向,因为案例数量越来越多。难道没有更聪明的方法吗o

  $('.list button').on('click', function() {
    if ($(this).closest('.list').prev().length === 0) {
      if ($(this).closest('.bloc').length) {
        $(this).closest('.bloc').prev('.list').addClass('active');
        $(this).closest('.bloc').prev('.bloc').find('.list:last-child').addClass('active');
      } else {
        $(this).closest('.list').next('.list').addClass('active');
      }
    }

    if ($(this).closest('.list').prev('.bloc').length) {
      $(this).closest('.list').prev('.bloc').find('.list:last-child').addClass('active');
    }
    $(this).closest('.list').prev('.list').addClass('active'); 
  }

不要使用
.closest
.prev和
.next
您可以使用to
.index
,它将为您提供现有集合中的索引

var idx = collection.index(element);
  • 将所有.list项选择到jquery对象/集合中
  • 单击“获取该集合中的索引”时
  • 减去1得到该集合中的上一个.list项
基本场景包含在
$(“.list”)
中:

//首先整理列表
变量列表=$(“.list”);
//添加单击处理程序
列表。单击(函数(){
//确认没有重复项
//与$(this).index()匹配,后者是父级中的索引
console.log(list.index(this),$(this.index())
$(.active”).removeClass(“active”);
var idx=list.index(本);
如果(idx>0)
列表.eq(idx-1).addClass(“活动”);
});
.list{边框:1px实心#CCC;高度:20px;}
.bloc{border:1px solid#444;padding:5px;}
.active{边框:1px实心红色;}

var idx = collection.index(element);