jQuery Object array notation

后端 未结 2 1122
忘掉有多难
忘掉有多难 2020-12-03 15:55

I\'m new to jQuery, and I\'m having a little trouble understanding its array notation for objects. Reading the jQuery docs and this article, it seems that you can refer to t

相关标签:
2条回答
  • 2020-12-03 16:08

    When you reference a jQuery object as an array you get a DOM element back. You'll need to convert it back to a jQuery object to use methods like .hide()

    var bar = $('.foo')[n];
    var $bar = $(bar);
    
    $bar.hide();
    

    Or just use jQuery's eq() method:

    var bar = $('.foo').eq(n);
    bar.hide();
    
    0 讨论(0)
  • 2020-12-03 16:24

    The [0] array notation and the .get() method both return a reference to a DOM element within the jQuery object, and you can't use jQuery methods on DOM elements.

    Try the eq() method instead, because it returns a new jQuery object:

    $('.foo').eq(0).hide();
    

    Note also that having used the array notation or .get() to get a reference to a DOM element means you can then get direct access to the DOM element's properties, e.g.:

    var firstElId = $('.foo')[0].id;
    

    ...with a second note that $('.foo')[0] will be undefined and $('.foo')[0].id will give an error if there are no elements matching the '.foo' selector.

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