如何实现“ prevUntil”?在没有库的Vanilla JavaScript中? [英] How to implement "prevUntil" in Vanilla JavaScript without libraries?

查看:115
本文介绍了如何实现“ prevUntil”?在没有库的Vanilla JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现jQuery的 prevUntil() 方法。

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

我在上面有几个< div> 元素

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

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

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.

如何实现?

推荐答案

此答案先前已发布

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

仅供参考:jQuery代码库是一个很好的观察资源

这里是一个出色的工具,可以非常简化地显示jQuery代码库。
http://james.padolsey.com/jquery/

这篇关于如何实现“ prevUntil”?在没有库的Vanilla JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆