I'm new to jQuery, apologies if this is a silly question.

When I use it find an element using the id, I know theres always one match and in order to access it I would use the index [0]. Is there a better way of doing this? For e.g.

var gridHeader = $("#grid_GridHeader")[0];

推荐答案

You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.

.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)

Jquery相关问答推荐

提交表单时运行自定义验证脚本

与其他 Javascript 框架相比,为什么 jQuery 被如此广泛地采用?

如何在 jQuery 中 Select 特定的表单元素?

Javascript 仅打印 iframe 内容

jQuery 绑定点击 *ANYTHING* 但 *ELEMENT*

在 jQuery UI Datepicker 中禁用future 日期

使用 jQuery 和 HTML 导出为 CSV

jQuery 的 ajax 默认超时值是多少?

在 jQuery 中将 JSON 数组转换为 HTML 表

javascript 正则表达式用于包含至少 8 个字符、1 个数字、1 个大写和 1 个小写的密码

如何在 jQuery .each() 的每次迭代之间添加暂停?

jquery-ui datepicker更改z-index

带有 jquery.animate() 的 CSS 旋转跨浏览器

使用 jquery 在 radio 上单击或更改事件

如何使用 jQuery 停止默认链接点击行为

JQuery - 如何根据值 Select 下拉项

jQuery slideUp().remove() 在删除发生之前似乎没有显示 slideUp 动画

我可以通过 JavaScript 禁用 CSS :hover 效果吗?

jQuery.active 函数

如何禁用由子元素触发的 mouseout 事件?