Maison  >  Questions et réponses  >  le corps du texte

原生 js 如何实现 jquery 的 closest()方法?

原生 js 如何实现 jquery 的 closest()方法?

情景: 想要查找某个元素的祖先元素, 中间不知相隔多少层? 但是又不想引入jquery整个库。


phpcn_u274phpcn_u2742775 Il y a quelques jours1767

répondre à tous(2)je répondrai

  • 数据分析师

    数据分析师2017-10-01 00:19:43

    Comment implémenter la méthode close() de jquery en js natif ? -PHP Chinese Q&A-Comment implémenter la méthode la plus proche() de jquery en js natif ? - Questions et réponses sur le site Web chinois PHP

    Veuillez regarder et apprendre.

    répondre
    0
  • 阿神

    阿神2017-02-14 13:31:54

    这个问题,你该让jquery回答啊....自己看下源码不就可以了

    closest: function( selectors, context ) {
        var cur,
            i = 0,
            l = this.length,
            matched = [],
            pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
                jQuery( selectors, context || this.context ) :
                0;
    
        for ( ; i < l; i++ ) {
            for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
    
                // Always skip document fragments
                if ( cur.nodeType < 11 && ( pos ?
                    pos.index( cur ) > -1 :
    
                    // Don't pass non-elements to Sizzle
                    cur.nodeType === 1 &&
                        jQuery.find.matchesSelector( cur, selectors ) ) ) {
    
                    matched.push( cur );
                    break;
                }
            }
        }
    
        return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
    },


    répondre
    0
  • Annulerrépondre