如何在没有库的情况下在 Vanilla JavaScript 中实现“prevUntil”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7354154/
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
How to implement "prevUntil" in Vanilla JavaScript without libraries?
提问by Francisc
I need to implement the functionality of jQuery's prevUntil()
method in Vanilla JavaScript.
我需要prevUntil()
在 Vanilla JavaScript 中实现 jQuery方法的功能。
I've got several <div>
elements on the same level:
我<div>
在同一级别有几个元素:
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
I'm trying to use an onclick
event to find the event.target
's previousSiblings
untila certain criteria is reached (for example, a class name match) then stop.
我正在尝试使用一个onclick
事件来查找event.target
'spreviousSiblings
直到达到某个条件(例如,类名匹配)然后停止。
How do I achieve this?
我如何实现这一目标?
回答by abbotto
This answer was previously published herein response to a similar question .
此答案先前已在此处发布以回答类似问题。
There are a few ways to do it.
有几种方法可以做到。
Either one of the following should do the trick.
以下任一方法都可以解决问题。
// 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: The jQuery code-base is a great resource for observing Grade A Javascript.
仅供参考:jQuery 代码库是观察 A 级 Javascript 的绝佳资源。
Here is an excellent tool that reveals the jQuery code-base in a very streamlined way.http://james.padolsey.com/jquery/
这是一个出色的工具,它以非常精简的方式展示了 jQuery 代码库。http://james.padolsey.com/jquery/
回答by Joe
回答by pimvdb
Use .children
in combination with .parentNode
. Then filter the NodeList
, after converting it into an array: http://jsfiddle.net/pimvdb/DYSAm/.
使用.children
与组合.parentNode
。然后过滤NodeList
, 将其转换为数组后:http://jsfiddle.net/pimvdb/DYSAm/。
var div = document.getElementsByTagName('div')[0];
var siblings = [].slice.call(div.parentNode.children) // convert to array
.filter(function(v) { return v !== div }); // remove element itself
console.log(siblings);
回答by ?ime Vidas
How about this:
这个怎么样:
while ( node = node.previousElementSibling ) {
if ( ( ' ' + node.className + ' ' ).indexOf( 'foo' ) !== -1 ) {
// found; do your thing
break;
}
}
Don't bother telling me that this doesn't work in IE8...
不要打扰告诉我这在 IE8 中不起作用......
回答by John Hartsock
There is a previousSibling property in the HTML DOM
HTML DOM 中有一个 previousSibling 属性
Here is some reference
这里有一些参考
http://reference.sitepoint.com/javascript/Node/previousSibling
http://reference.sitepoint.com/javascript/Node/previousSibling
回答by wesbos
Just take a look at how jQuery does it.
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
Which uses a while / looping function caled dir(). The prevUntil just keeps going until previousSibling
is the same as the until
element.
它使用名为 dir() 的 while / 循环函数。prevUntil 会一直运行直到previousSibling
与until
元素相同。
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
回答by LogicalBranch
You could use indexOf
to determine if the index of the siblings are less than the index of the target element:
您可以使用indexOf
来确定兄弟元素的索引是否小于目标元素的索引:
// jshint esversion: 9
// get the target node
const node = document.querySelector("div:nth-child(3)");
// get the target node's index
const node_index = node.parentNode.indexOf(node);
// get the siblings of the target node
const siblings = node => [...node.parentNode.children].filter(child =>
child !== node
);
console.log(siblings);
// get the prevUntil
const class_name = "\bmy_class\b";
const prevUntil = siblings.filter((sibling, i) =>
i < node_index && (sibling.getAttribute("class") || "").includes(class_name)
);
console.log(prevUntil);
Good luck.
祝你好运。