Is there a fancier way to get a previous item with the same class?

前端 未结 1 1662
有刺的猬
有刺的猬 2021-01-22 17:05

I have table rows like so:


   ...



        
相关标签:
1条回答
  • 2021-01-22 17:27

    jQuery does not have something better than your option B. I've long thought this was a missing piece of functionality as I've regularly wanted something like it too. Fortunately, it's not too hard to make your own method:

    jQuery.fn.prevFind = function(selector) {
        var elems = [];
        this.each(function(i, item) {
            while (item = item.previousSibling) {
                if (item.nodeType == 1) {
                    if ($(item).is(selector)) {
                        elems.push(item);
                        break;
                    }
                }
            }
        });
        return(this.pushStack(elems, "prevFind", selector));
    }
    

    The same could be done for a nextFind() also.

    In your example, instead of this:

    $(this).prevAll("parent" + parentId).eq(0);
    

    you would use this:

    $(this).prevFind("parent" + parentId)
    

    And, here's an implementation of both prevFind() and nextFind() that uses some common code:

    (function($) {
    
        $.each({
            'prevFind' : 'previousSibling',
            'nextFind' : 'nextSibling'
        }, function(method, dir) {
    
            $.fn[method] = function (selector) {
    
                var elems = [];
    
                this.each(function(i, item) {
                    while (item = item[dir]) {
                        if (item.nodeType == 1) {
                            if ( $.find.matches(selector, [item]).length ) {
                                elems.push(item);
                                break;
                            }
                        }
                    }
                });
    
                return this.pushStack(elems, method, selector);
            };
        });
    
    }(jQuery));
    

    Here's the fiddle: http://jsfiddle.net/nDYDL/1/

    0 讨论(0)
提交回复
热议问题