javascript 原版javascript中的jQuery index()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13658021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:23:38  来源:igfitidea点击:

jQuery index() in vanilla javascript

javascriptjquery

提问by pala?н

As per the jQuery api, the complementary operation to .get(), which accepts an index and returns a DOM node, .index()can take a DOM node and returns an index. Suppose we have a simple unordered list on the page:

根据 jQuery api,.get() 的补充操作,它接受一个索引并返回一个 DOM 节点,.index()可以接受一个 DOM 节点并返回一个索引。假设我们在页面上有一个简单的无序列表:

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>

.index()will return the position of the first element within the set of matched elements in relation to its siblings:

.index()将返回匹配元素集合中第一个元素相对于其兄弟元素的位置:

alert('Index: ' + $('#bar').index();

We get back the zero-based position of the list item:

我们取回列表项从零开始的位置:

Index: 1

I just want to know, how can we do the same using JavaScript??

我只想知道,我们如何使用JavaScript做同样的事情??

采纳答案by Denys Séguret

You can build your own function :

您可以构建自己的函数:

function indexInParent(node) {
    var children = node.parentNode.childNodes;
    var num = 0;
    for (var i=0; i<children.length; i++) {
         if (children[i]==node) return num;
         if (children[i].nodeType==1) num++;
    }
    return -1;
}

Demonstration (open the console)

演示(打开控制台)

回答by vsync

I've modified Travis J answerto not include TextNodes and made a function out of it.

我已经修改了Travis J 的答案,使其不包含 TextNodes 并从中创建了一个函数。

You can run it in the console and see (on stackoverflow).

您可以在控制台中运行它并查看(在 stackoverflow 上)。

Classic way:

经典方式:

function getNodeindex( elm ){ 
    var c = elm.parentNode.children, i = 0;
    for(; i < c.length; i++ )
        if( c[i] == elm ) return i;
}

// try it
var el = document.getElementById("sidebar");
getNodeindex(el);

With ES2015:

使用 ES2015:

function getNodeindex( elm ){ 
    return [...elm.parentNode.children].findIndex(c => c == elm)
    // or
    return [...elm.parentNode.children].indexOf(elm)
}

Demo:

演示:

const getNodeindex = elm => [...elm.parentNode.children].indexOf(elm)
<button onclick="console.log(  getNodeindex(this)  )">get index</button>
<button onclick="console.log(  getNodeindex(this)  )">get index</button>
<button onclick="console.log(  getNodeindex(this)  )">get index</button>



I also want to point to another thread on the same matter, which has a great answer(for people seeking older IE support)

我还想指出关于同一问题的另一个线程,它有一个很好的答案(对于寻求旧版 IE 支持的人)

回答by fregante

No loops needed, call Array#indexOfon .parentElement.children:

无回路需要,调用Array#indexOf.parentElement.children

const element = document.querySelector('#baz');

[].indexOf.call(element.parentElement.children, element);
// => 2

You can even call it on a random list of elements, just like you can in jQuery:

你甚至可以在一个随机的元素列表上调用它,就像在 jQuery 中一样:

const list = document.querySelectorAll('li');
const element = document.querySelector('#baz');

[].indexOf.call(list, element);
// => 2

回答by Corey Young

You can find this information out by going up the dom tree using previousElementSibling and incrementing.

您可以通过使用 previousElementSibling 和递增在 dom 树中查找此信息。

var getElementIndex(element) {
    if (!element) {
        return -1;
    }
    var currentElement = element,
        index = 0;

    while(currentElement.previousElementSibling) {
        index++;
        currentElement = currentElement.previousElementSibling;
    }
    return index
}

getElementIndex(document.getElementById('#bar'));

here is the browser support for previousElementSibling:

这是对 previousElementSibling 的浏览器支持:

https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling

https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling