jQuery:find()子项,直到遇到某个阈值元素

Mik*_*maa 12 jquery

我有一个嵌套的表结构

   <table>

       <td id="first">

           <div class="wrapper">
               <input name=1>
           </div>

           <input name=2>

           <table>

               <td id="second">

                   <input name=3>
Run Code Online (Sandbox Code Playgroud)

我有jQuery选择$("#first").我想在这种情况下遍历和find()所有的孩子,但不要下降到嵌套的s.<input>s<td><table>

所以我需要一个jQuery技巧

  • find()所有子元素都元素化

  • 将在DOM树中下降n级

  • 但是如果<table>遇到某个元素(),将停止下降,以便选择器不选择嵌套表的输入(将单独处理)

  • 可以有任意数量的嵌套<table>级别,因此无论在$("#first")或任何其他范围内遇到多少父<table>或子,解决方案都应该有效<table><td><td>

我检查了其他jQuery发现直到问题.他们有答案,但似乎他们没有填写最后的标准

Gar*_*orn 5

我在另一个问题上遇到了类似的问题.我最后在与一些人试图想到一个找到选择器来回来之后最终找到了一个插件.

用法: ExclusiveInputs = $('#first').findExclude('input','table');

// 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
    var result = typeof result !== 'undefined' ?
                result :
                new jQuery();

    // Iterate through all children, except those match Mask
    this.children().each(function(){

        var 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;
}
Run Code Online (Sandbox Code Playgroud)

(简明版):

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