12

prevUntil()Vanilla JavaScriptで jQuery のメソッドの機能を実装する必要があります。

同じレベルにいくつかの<div>要素があります。

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

onclickイベントを使用して を検索し、特定の基準 (クラス名の一致など) に達してから停止event.targetしよpreviousSiblings としています。

どうすればこれを達成できますか?

4

7 に答える 7

8

previousElementSibling の使用:

    var className = "needle";
    var element = clickedElement;
    while(element.previousElementSibling && element.previousElementSibling.className != className) {
       element = element.previousElementSibling;
    }
    element.previousElementSibling; // the element or null
于 2011-09-08T20:45:23.317 に答える
6

.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);
于 2011-09-08T20:43:44.993 に答える
3

これはどう:

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

これが IE8 では動作しないことを気にしないでください...

于 2011-09-08T20:46:04.487 に答える
2

HTML DOM に previousSibling プロパティがあります

ここにいくつかの参照があります

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

于 2011-09-08T20:40:52.980 に答える
2

jQuery がどのようにそれを行うかを見てみましょう。

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

dir() と呼ばれる while / looping 関数を使用します。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;
},
于 2011-09-08T20:42:32.840 に答える
1

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

幸運を。

于 2019-10-21T14:53:32.867 に答える