获取兄弟姐妹的JavaScript,没有图书馆 [英] Get siblings in JavaScript, without libraries
问题描述
如何使用JavaScript寻找向上的兄弟姐妹?
基本上,我需要一个与jQuery中存在的函数类似的 prevUntil()
函数。
How can I look for siblings "upwards" using JavaScript?
Basically, I need a prevUntil()
function similar to the one present in jQuery.
有很多< div>
元素,都在同一级别,例如:
I have lots of <div>
elements, all on the same level, such as:
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
我想从一个点击的元素开始,并且在兄弟姐妹树上工作,直到匹配达到班级名称标准,然后停止。
I want to start at a clicked element, and work my way up the siblings tree until one that matches a class name criteria is reached, then stop.
请问如何做?
推荐答案
此回答以前发布这里回复类似的问题。
This answer was previously published here in response to a similar question .
有几种方法可以实现。
以下任何一个都可以做到这一点。
// METHOD A (ARRAY.FILTER, STRING.INDEXOF)
var siblings = function(node, children) {
siblingList = children.filter(function(val) {
return [node].indexOf(val) != -1;
});
return siblingList;
}
// METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
var siblings = function(node, children) {
var siblingList = [];
for (var n = children.length - 1; n >= 0; n--) {
if (children[n] != node) {
siblingList.push(children[n]);
}
}
return siblingList;
}
// METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
var siblings = function(node, children) {
siblingList = children;
index = siblingList.indexOf(node);
if(index != -1) {
siblingList.splice(index, 1);
}
return siblingList;
}
FYI:jQuery代码库是一个很好的观察资源A级Javascript。
这是一个非常优秀的工具,以非常流畅的方式揭示了jQuery代码库。
http://james.padolsey.com/jquery/
这篇关于获取兄弟姐妹的JavaScript,没有图书馆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!