如何优雅地索引jQuery对象数组?(How do I index an array of jQuery objects elegantly?)

编程入门 行业动态 更新时间:2024-10-27 06:24:32
如何优雅地索引jQuery对象数组?(How do I index an array of jQuery objects elegantly?)

我发现自己开始写这个:

$($("a-selector-which-returns-multiple-objects")[index]).SomejQueryFunctionForExampleShow()

因为我有一个查询返回多个对象,所以[index]操作符返回DOM对象,而不是一个jQuery对象,因此我将其转换回带有外部$()的jQuery对象。

这工作正常,但似乎不雅,我觉得我错过了一些关于索引到jQuery对象集 - 什么是正确的方法来做到这一点?

I find myself starting to write this:

$($("a-selector-which-returns-multiple-objects")[index]).SomejQueryFunctionForExampleShow()

Because I have one query which returns multiple objects, then the [index] operator returns the DOM object, not a jQuery object, so I convert it back to a jQuery object with the outer $().

This is working fine, but seems inelegant, and I feel I'm missing something about indexing into sets of jQuery objects - what's the proper way to do this?

最满意答案

在你描述的情况下,你根本不必索引你的元素。 由于JQuery链接其命令的方式,您将在前一个选择器返回的所有元素上运行任何命令。

以下示例将隐藏所有<a>元素:

$(document).ready(function() { $("a").hide(); });

如果它需要是一个特定的元素,你应该给它一个唯一的ID来选择:

$(document).ready(function() { $("#my-unique-id").hide(); });

如果你想返回一个特定的索引作为JQuery对象,你应该使用eq函数 。

$(document).ready(function() { $("a").eq(0).hide(); });

但是,就你而言,你根本不需要索引。

You don't have to index your elements at all in the case you describe. Because of the way JQuery chains its commands, any command you will be run on all the elements the previous selector returns.

The following example will hide all <a> elements:

$(document).ready(function() { $("a").hide(); });

If it needs to be a specific element, you should be giving it a unique ID to select:

$(document).ready(function() { $("#my-unique-id").hide(); });

If you want to return a specific index as a JQuery object, you should use the eq function.

$(document).ready(function() { $("a").eq(0).hide(); });

But again, in your case, you don't need the index at all.

更多推荐

本文发布于:2023-04-29 10:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   优雅   对象   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!