jQuery ancestors using jQuery objects

前端 未结 7 1748
北荒
北荒 2021-01-02 18:33

I\'d like to check ancestry using two jQuery objects. They don\'t have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called get()

相关标签:
7条回答
  • 2021-01-02 18:56

    You can use the index() method to check if an element exists in a list, so would the following work?

    var someDiv = $('#div');
    
    $('a').click(function() {
        if ($(this).parents().index(someDiv) >= 0) {
            alert('boo');
        }
    }
    

    From #index reference.

    0 讨论(0)
  • 2021-01-02 18:56
    var $element = $('a');
    while ($element && !$element.is('someDiv')) {
       var $element = $element.parent();
    };
    
    0 讨论(0)
  • 2021-01-02 18:57

    Along those lines, parents() optionally accepts a selector itself:

    $('a').click(function() {
      if ($(this).parents("#div").length) {
        alert('boo');
      }
    });
    
    0 讨论(0)
  • 2021-01-02 18:59

    Checking for (this).parents().index(someDiv) >= 0, as @Gareth suggests, will work just fine.

    However, using the jQuery ancestry plugin is way faster / more efficient.

    0 讨论(0)
  • 2021-01-02 18:59

    Would you not get the result you want from simply using a CSS selector?

    $( '#div a' ).click( function() { ... } );
    
    0 讨论(0)
  • 2021-01-02 19:00

    One way would be to use the filter function

    $('a').click(function() {
        $(this).parents().filter(function() {
           return this == someDiv[0];
        }).each(function() {
           alert('foo');
        })
    }
    

    I think you may also be able to get away with using jQuery.inArray

    if ($.inArray( someDiv, $(this).parents() ) ) {
            alert('boo');
    }
    
    0 讨论(0)
提交回复
热议问题