【问题标题】:get the index of element I select using .filter使用 .filter 获取我选择的元素的索引
【发布时间】:2021-03-31 11:32:50
【问题描述】:

我想获取我使用.filter 选择的元素的索引。代码如下所示:

abc = $('.abc').find('.el').clone();
log = abc.filter('.def');

我得到了元素,但我需要它的索引(比如 abc 中克隆数据中的第 n 个子位置。我该如何实现?

【问题讨论】:

    标签: javascript jquery filter


    【解决方案1】:

    您可以使用index() 的以下变体:

    如果在一个元素集合和一个 DOM 元素上调用 .index() 或者传入 jQuery 对象,.index() 返回一个整数 指示传递的元素相对于原​​始元素的位置 收藏。

    var index = abc.index(log);
    

    【讨论】:

      【解决方案2】:

      你可以使用indexOf

      let array = ['.a', '.de', '.def']
      let index = array.indexOf('.def')
      console.log(index) // 2
      
      // if index > -1, it exists in the array
      
      let array = ['.a', '.de']
      let index = array.indexOf('.def')
      console.log(index) // -1
      

      【讨论】:

      • abc 将是一个 jQuery 对象,而不是一个数组
      猜你喜欢
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多