无论如何从$(".box")获取索引项

Jie*_*eng 0 javascript jquery

假设我得到了一些项目列表$(".box").是否有可能获得索引的jQuery对象

喜欢

var $boxes = $(".box"),
    $box2 = $boxes[1]
Run Code Online (Sandbox Code Playgroud)

目前我做的事情就像

var $boxes = $(".box");
$boxes.each(function(i, box) {
    var $box = $(box); // <-- is this a good idea?
    // do something with $box
});
Run Code Online (Sandbox Code Playgroud)

我想知道这条线var $box = $(box)是不是一个好主意?我实际上是在运行它setInterval()

喜欢

var $boxes = $(".box");
setInterval(function() {
    $boxes.each(function(i, box) {
        var $box = $(box); // <-- is this a good idea?
        // do something with $box
    });
}, 1000);
Run Code Online (Sandbox Code Playgroud)

我想知道它是否对性能有害,因为我$boxes在这个例子中为每1s中的每个项初始化一个变量.如果我可以直接从jQuery"数组"或任何$ box访问元素,它可能更好?

T.J*_*der 5

目前还不完全清楚你的问题是什么,但jQuery对象已经是类似数组的,你可以[]在它们上使用运算符.你得到的是该索引处的原始DOM对象,因此:

var $boxes = $(".box"),
    box2 = $boxes[1],   // `box2` is a raw DOM object
    $box2 = $(box2);    // `$box2` is a jQuery wrapper around the second box
Run Code Online (Sandbox Code Playgroud)

关于这段代码:

var $boxes = $(".box");
setInterval(function() {
    $boxes.each(function(i, box) {
        var $box = $(box); // <-- is this a good idea?
        // do something with $box
    });
}, 1000);
Run Code Online (Sandbox Code Playgroud)

如果您确实需要这样做(例如,如果您确实需要围绕该特定条目的jQuery包装器),那么这样做很好.它使浏览器的每一次做工作的时间间隔定时器触发(因为$()不是免费的,但它并不昂贵要么),因此,如果该列表是短暂的,你可以通过创建预jQuery的包装买卖该CPU时间,内存使用在元素上:

var $wrapped = [];
$(".box").each(function() {
    $wrapped.push($(this));
});
setInterval(function() {
    $.each($wrapped, function(i, $box) {
        // do something with $box
    });
}, 1000);
Run Code Online (Sandbox Code Playgroud)