Skip recursion in jQuery.find() for a selector?

后端 未结 8 1062
孤独总比滥情好
孤独总比滥情好 2020-12-18 05:31

TL;DR: How do I get an action like find(), but block traversal (not full stop, just skip) for a certain selector?

ANSWERS: $(Any).fin

8条回答
  •  执念已碎
    2020-12-18 06:26

    Well, I really don't want to be answering my own question on a bounty, so if anyone can provide a better or alternative implementation please do..

    However, being pressed to complete the project, I ended up working on this quite a bit and came up with a fairly clean jQuery plugin for doing a jQuery.find() style search while excluding child branches from the results as you go.

    Usage to work with sets of elements inside nested views:

    // Will not look in nested ul's for inputs
    $('ul').findExclude('input','ul');
    
    // Will look in nested ul's for inputs unless it runs into class="potato"
    $('ul').findExclude('input','.potato');
    

    More complex example found at http://jsfiddle.net/KX65p/3/ where I use this to .each() a nested class and bind elements which occur in each nested view to a class. This let me make components server-side and client-side reflect each other's properties and have cheaper nested event handling.

    Implementation:

    // Find-like method which masks any descendant
    // branches matching the Mask argument.
    $.fn.findExclude = function( Selector, Mask, result){
    
        // Default result to an empty jQuery object if not provided
        result = typeof result !== 'undefined' ?
                    result :
                    new jQuery();
    
        // Iterate through all children, except those match Mask
        this.children().each(function(){
    
            thisObject = jQuery( this );
            if( thisObject.is( Selector ) ) 
                result.push( this );
    
            // Recursively seek children without Mask
            if( !thisObject.is( Mask ) )
                thisObject.findExclude( Selector, Mask, result );
        });
    
        return result;
    }
    

    (Condensed Version):

    $.fn.findExclude = function( selector, mask, result )
    {
        result = typeof result !== 'undefined' ? result : new jQuery();
        this.children().each( function(){
            thisObject = jQuery( this );
            if( thisObject.is( selector ) ) 
                result.push( this );
            if( !thisObject.is( mask ) )
                thisObject.findExclude( selector, mask, result );
        });
        return result;
    }
    

提交回复
热议问题