开发者

Retrieving an element by array index in jQuery vs the each() function

开发者 https://www.devze.com 2022-12-25 23:02 出处:网络
I was writing a \"pluginable\" function when I noticed the following behavior (tested in FF 3.5.9 with Firebug 1.5.3).

I was writing a "pluginable" function when I noticed the following behavior (tested in FF 3.5.9 with Firebug 1.5.3).

$.fn.computerMove = function () {
    var board = $(this);
    var emptySquares = board.find('div.clickable');
    var randPosition = Math.floor(Math.random() * emptySquares.length);


    emptySquares.each(function (index) {
        if (index === randPosition) {
            // logs a jQuery object
            console.log($(this));
        }
    });

    target = emptySquares[randPosition];
    // logs a non-jQuery object
    console.log(target);
    // throws error: attr() not a function for target
    board.placeMark({'position' : target.attr('id')});
}

I noti开发者_如何学Goced the problem when the script threw an error at target.attr('id') (attr not a function). When I checked the log, I noticed that the output (in Firebug) for target was:

<div style="width: 97px; height: 97px;" class="square clickable" id="8"></div>

If I output $(target), or $(this) from the each() function, I get a nice jQuery object:

[ div#8.square ]

Now here comes my question: why does this happen, considering that find() seems to return an array of jQuery objects? Why do I have to do $() to target all over again?

[div#0.square, div#1.square, div#2.square, div#3.square, div#4.square, div#5.square, div#6.square, div#7.square, div#8.square]

Just a curiosity :).


.find() returns not an array of jQuery objects, but one jQuery object containing an array of DOM elements (a jQuery object, at it's core, is a wrapper around a DOM element array).

When you're iterating through, each element you're on is a DOM element. So, it needs to be wrapped in $(this) to become jQuery object and have access to those methods.

Also as a side note: The id attribute can't begin with a number, since it's invalid HTML you may or may not experience strange behavior, especially cross-browser (this rule applies for any invalid HTML).


No, the find method doesn't return an array of jQuery objects. You are creating a jQuery object for each element here:

console.log($(this));

If you log the value without creating a jQuery object from it:

console.log(this);

you will see that it's an element, not a jQuery object.

When you access the jQuery object as an array, you get an element. If you want a jQuery object you have to create one from the element.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号