在vanilla javascript中的jQuery index() [英] jQuery index() in vanilla javascript
本文介绍了在vanilla javascript中的jQuery index()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据jQuery api,对.get()的补充操作,它接受一个索引并返回一个DOM节点, .index()
可以带一个DOM节点并返回一个索引。假设我们在页面上有一个简单的无序列表:
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:
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
.index()
将返回头寸匹配元素集合中与其兄弟姐妹相关的第一个元素:
.index()
will return the position of the first element within the set of matched elements in relation to its siblings:
alert('Index: ' + $('#bar').index();
我们回到列表项的从零开始的位置:
We get back the zero-based position of the list item:
Index: 1
我只是想知道,我们怎样才能使用 JavaScript ??
I just want to know, how can we do the same using JavaScript??
推荐答案
你可以构建自己的函数:
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;
}
这篇关于在vanilla javascript中的jQuery index()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文