jQuery to find all previous elements that match an expression

后端 未结 5 2048
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 16:21

Using jQuery, how do you match elements that are prior to the current element in the DOM tree? Using prevAll() only matches previous siblings.<

5条回答
  •  悲&欢浪女
    2020-12-05 16:33

    edit: this solution works for both your original problem, the problem you mention in your first comment, and the problem you detail in the comment after that.

    $('.myLinks').click(function() {
        var findMe = '';
    
        $(this).parents().each(function() {
            var a = $(this).find('.findme').is('.findme');
            var b = $(this).find('.myLinks').is('.myLinks');
            if (a && b) {                             // look for first parent that
                                                      // contains .findme and .myLinks
                $(this).find('*').each(function() {
                    var name = $(this).attr('class');
                    if ( name == 'findme') {
                        findMe = $(this);             // set element to last matching
                                                      // .findme
                    }
                    if ( name == 'myLinks')    {
                        return false;                 // exit from the mess once we find
                                                      // .myLinks
                    }
                });
                return false;
            }   
        });
        alert(findMe.text() );               // alerts "find this one"
    });
    

    this works for your example in the OP as well as a modified example as explained in the comments:

    don't find this one
    find this one
    find the previous .findme
    don't find this one

    as well as this test case which you added:

    don't find this one
    don't find this one
    find this one
    find the previous .findme

提交回复
热议问题