迭代jQuery集合而无需重建jQuery对象 [英] Iterate over a jQuery collection without having to rebuild the jQuery object

查看:114
本文介绍了迭代jQuery集合而无需重建jQuery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(".item").each (i, elt) ->
    $(elt).attr("href")
    # ...

执行 $(elt)是获取jquery对象的必要条件。有没有办法迭代jquery集合,而不必重建jquery对象?

Doing $(elt) is necessery to get the jquery object. Is there a way to iterate over a jquery collection, without having to rebuild the jquery object?

推荐答案


做$(elt)是获得jquery对象的必要条件。

Doing $(elt) is necessery to get the jquery object.

是。


有没有办法迭代jquery集合,而不必重建jquery对象?

Is there a way to iterate over a jquery collection, without having to rebuild the jquery object?

没有。因为你拥有的jQuery对象是一组所有匹配的元素。要在单个元素上使用jQuery方法,您需要获取一个jQuery对象,该对象仅包含您要操作的单个元素。在循环中,这意味着包装 elt (或,因为两者都是相同的DOM元素)。

No. Because the jQuery object you have is a set of all of the matched elements. To use the jQuery methods on individual elements, you need to get a jQuery object containing just the individual element you want to act on. In a loop, that means wrapping your elt (or this, as both are the same DOM element).

但是,对于很多事情,你不需要需要 jQuery方法。你的例子就是其中之一,直接使用 elt.href

For lots of things, though, you don't need jQuery methods. Your example is one of those things, just use elt.href directly:

$(".item").each (i, elt) ->
    var someVar = elt.href;
    # ...

DOM2 HTML规范和更新的 HTML5规范都列出了可以直接使用的大量反射属性。例如, id 是人们经常使用的一个。你看 $(this).attr(id)很多 this.id 就足够了(和效率更高,尽管效率极为罕见)。

The DOM2 HTML spec and the newer HTML5 spec both list lots of reflected properties you can use directly. id, for instance, is one in particular people frequently use. You see $(this).attr("id") a lot where this.id would be sufficient (and more efficient, although it's extremely rare that the efficiency matters).

这篇关于迭代jQuery集合而无需重建jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆