Javascript 通过jQuery中的数组索引检索元素与each()函数的比较

Javascript 通过jQuery中的数组索引检索元素与each()函数的比较,javascript,jquery,Javascript,Jquery,我正在编写一个可插入的函数,这时我注意到在FF3.5.9中使用Firebug 1.5.3测试了以下行为 $.fn.computerMove = function () { var board = $(this); var emptySquares = board.find('div.clickable'); var randPosition = Math.floor(Math.random() * emptySquares.length); emptySqua

我正在编写一个可插入的函数,这时我注意到在FF3.5.9中使用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')});
}
当脚本在target.attr'id'attr不是函数时,我注意到了这个问题。当我检查日志时,我注意到Firebug for target中的输出是:

<div style="width: 97px; height: 97px;" class="square clickable" id="8"></div>
现在我的问题来了:考虑到find似乎返回jQuery对象数组,为什么会发生这种情况?为什么我要再次做$target

[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]
只是好奇:.

.find返回的不是jQuery对象数组,而是一个包含DOM元素数组的jQuery对象。jQuery对象的核心是DOM元素数组的包装器

当您在其中进行迭代时,所使用的每个元素都是一个DOM元素。因此,它需要包装在$this中,才能成为jQuery对象并访问这些方法

另请注意:id属性不能以数字开头,因为它是无效的HTML,您可能会也可能不会遇到奇怪的行为,尤其是跨浏览器。此规则适用于任何无效的HTML。

否,find方法不会返回jQuery对象数组。您正在为此处的每个元素创建jQuery对象:

console.log($(this));
如果记录该值而不从中创建jQuery对象:

console.log(this);
您将看到它是一个元素,而不是jQuery对象


当您以数组的形式访问jQuery对象时,会得到一个元素。如果需要jQuery对象,则必须从元素创建一个对象。

可能不相关,但html id应该以a-zA-Z开头。Try target=emptySquares.find':eq'+randPosition+;在回答这个问题时,我忘记了如何做的部分:为此,请使用emptySquares.eqrandPosition在该位置获得一个基于0的jQuery元素。+1。因此:document.getElementById;等于$id[0];
console.log(this);