简体   繁体   English

如何使用 jquery 或 vanilla js 在 li 中找到元素的位置

[英]How to find the position for an element in a li with jquery or vanilla js

Lets imagine I have the following HTML code.假设我有以下 HTML 代码。

I need to find the position within the LI elements for the LI which has the class focus applied.我需要在应用了类焦点的 LI 元素中找到位置。

In this example the result should be 2 (if at 0 index).在此示例中,结果应为 2(如果索引为 0)。 Any idea how to do it?知道怎么做吗?

<ul class="mylist">
    <li>Milk</li>
    <li>Tea</li>
    <li class="focus">Coffee</li>
</ul>

In pure JavaScript:在纯 JavaScript 中:

var index = 0;
var lis = document.getElementsByTagName('li');
for (var len = lis.length; index < len; ++index) {
    if (lis[index].className.match(/\bfocus\b/)) {
        break;
    }
}

(fiddle) (小提琴)

While you've already accepted an answer to your question, I thought I'd put together a simple index() method for HTMLElement s:虽然您已经接受了问题的答案,但我想我应该为HTMLElement s 组合一个简单的index()方法:

HTMLElement.prototype.index = function () {
    var self = this,
        parent = self.parentNode,
        i = 0;
    while (self.previousElementSibling){
        i++;
        self = self.previousElementSibling
    }
    return this === parent.children[i] ? i : -1;
}

var focus = document.querySelector('li.focus'),
    i = focus.index();
console.log(i); // 2

JS Fiddle demo . JS小提琴演示

References:参考:

Use .index()使用.index()

var index = $('.focus').index();

DEMO演示

Specific list具体清单

$('.mylist .focus').index()

DEMO演示

In jQuery, you should be able to get it, via index .在 jQuery 中,您应该能够通过index获得它。 With classes, you could run into issues, when having multiple of them.对于类,当有多个类时,您可能会遇到问题。

I prepared a Plunker , where you can see a solution to the problem.我准备了一个Plunker ,您可以在其中查看问题的解决方案。

the expanded version (jquery) would be扩展版本(jquery)将是

$(document).ready(function(){
 $('li').each(function(){
  var cls=$(this).attr('class');
  if(cls=='focus'){
   alert($(this).index());
  }
 });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM