jQuery .prev() of a type regardless of it's parent etc

后端 未结 3 997
遇见更好的自我
遇见更好的自我 2021-01-27 14:38

is there a simple way to get the previous occurrence of an element in the DOM? If I\'m looking at #text3 and I want to get ahold of the previous input #text2<

相关标签:
3条回答
  • 2021-01-27 14:59

    I've created a new jQuery plugin which returns the "real" previous input element. Include this code:

    (function($){
        $.fn.realPrev = function(selector){
            var thisElem = this.get(0); //Get DOM element for comparison
            var lastElement, foundElement = null;
            $(selector).each(function(){
                if(this == thisElem){
                    foundElement = lastElement;
                    return false;
                }
                lastElement = this;
            });
            return $(foundElement);
        }
    })(jQuery);
    

    Usage:

    $("#input3").realPrev("input");
    

    Fiddle: http://jsfiddle.net/QWRWh/

    0 讨论(0)
  • 2021-01-27 15:08

    You can use $.index(), like so:

    var previous = null;
    var inputs = $('input');
    var index = inputs.index(this);
    if (index > 0) {
        previous = $(inputs[index-1])
    }
    

    For example: http://jsfiddle.net/pYaBL/1/

    0 讨论(0)
  • 2021-01-27 15:21

    Both other answers assume that the element you are using is of the same type of the element you're looking for. If it's arbitrary, this should work (performance not be great on larger files).

    Sort of combining the two other answers:

    (function($){
        $.fn.realPrev = function(selector){
            var all = $("*");
    
            return all.slice(0,all.index(this)).filter(selector).last();
        }
    })(jQuery);
    

    http://jsfiddle.net/QWRWh/1/

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