如何实现“prevUntil”在没有库的 Vanilla JavaScript 中?

发布于 2024-12-03 15:54:53 字数 533 浏览 1 评论 0原文

我需要在 Vanilla 中实现 jQuery 的 prevUntil() 方法的功能JavaScript。

我在同一级别上有多个

元素:

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

我正在尝试使用 onclick 事件来查找 event.targetpreviousSiblings 直到达到特定条件(例如,类名匹配),然后停止。

我该如何实现这一目标?

I need to implement the functionality of jQuery's prevUntil() method in Vanilla JavaScript.

I've got several <div> elements on the same level:

<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 until a certain criteria is reached (for example, a class name match) then stop.

How do I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

羁拥 2024-12-10 15:54:54

.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);

Use .children in combination with .parentNode. Then filter the NodeList, after converting it into an array: 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);
莳間冲淡了誓言ζ 2024-12-10 15:54:54

怎么样:

while ( node = node.previousElementSibling ) {
    if ( ( ' ' + node.className + ' ' ).indexOf( 'foo' ) !== -1 ) {
        // found; do your thing
        break;
    }
}

别费心告诉我这在 IE8 中不起作用......

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...

青衫负雪 2024-12-10 15:54:54

只需看看 jQuery 是如何实现的

prevUntil: function( elem, i, until ) {
    return jQuery.dir( elem, "previousSibling", until );
},

它使用一个名为 dir() 的 while/循环函数。 prevUntil 一直持续到 previousSiblinguntil 元素相同为止。

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;
},

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: 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;
},
野の 2024-12-10 15:54:54

HTML DOM 中有一个 previousSibling 属性

这是一些参考

http://reference.sitepoint.com/ javascript/Node/previousSibling

There is a previousSibling property in the HTML DOM

Here is some reference

http://reference.sitepoint.com/javascript/Node/previousSibling

挽袖吟 2024-12-10 15:54:54

您可以使用 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);

祝你好运。

You could use indexOf to determine if the index of the siblings are less than the index of the target element:

// 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.

虐人心 2024-12-10 15:54:53

此答案之前已在此处发布作为回应类似的问题。

有几种方法可以做到这一点。

以下任一方法都可以解决问题。

// 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;
}

仅供参考:jQuery 代码库是观察成绩的重要资源Javascript。

这是一个优秀的工具,它以非常简化的方式揭示 jQuery 代码库。
http://james.padolsey.com/jquery/

This answer was previously published here in 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.

Here is an excellent tool that reveals the jQuery code-base in a very streamlined way.
http://james.padolsey.com/jquery/

水水月牙 2024-12-10 15:54:53

示例
使用 previousElementSibling:

    var className = "needle";
    var element = clickedElement;
    while(element.previousElementSibling && element.previousElementSibling.className != className) {
       element = element.previousElementSibling;
    }
    element.previousElementSibling; // the element or null

Example
Using previousElementSibling:

    var className = "needle";
    var element = clickedElement;
    while(element.previousElementSibling && element.previousElementSibling.className != className) {
       element = element.previousElementSibling;
    }
    element.previousElementSibling; // the element or null
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文