使用jQuery在元素数组中查找元素的位置

时间:2019-02-07 19:08:55

标签: javascript jquery

我有两个数组,分别表示排序前后的状态:

var $before = $('li');
// SORTING
var $after = $('li');

现在,我想选择一个特定的项目var $item = $after.filter(':first-child')并找到它在$ before列表中的位置。到目前为止,我正在做什么:

var beforeIndex = false;

$.each($before, function(i, v) {

  if($(v)[0] == $item[0]) {

    beforeIndex = i;

  }

})

但是,我觉得应该有一个更简单的解决方案,例如:

$before.find(x => $(x)[0] == $item[0]);

(不起作用)。有任何想法吗? :)

2 个答案:

答案 0 :(得分:0)

您可以按照以下步骤解决此问题。我试图用一个最小的例子。

var $li = $("ul > li");
var $item = $li.filter(':last-child');

var result = Array.prototype.findIndex.call($li, (li) => {
  return $item.is($(li));
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

答案 1 :(得分:0)

只需使用data属性,就无需查找它。

// Loop over the lis and set a data attribute with the index
$("li").each(function (index) {
  $(this).data("orginalIndex", index)
})

// some random sort code to change the order
$("ul").append($("li").sort(function(){
  return Math.random() > .5 ? 1 : -1
}))

// loop over the newly sorted lis and read the text and old index
$("li").each(function () {
  var elem = $(this);
  console.log(elem.text(), elem.data("orginalIndex"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

相关问题