Javascript 如何在 jQuery 中获取第一个元素而不是使用 [0]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3103810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get first element rather than using [0] in jQuery?
提问by Rubans
I'm new to jQuery, apologies if this is a silly question.
我是 jQuery 新手,如果这是一个愚蠢的问题,我深表歉意。
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.
当我使用它查找使用 id 的元素时,我知道总是有一个匹配项,为了访问它,我将使用索引 [0]。有没有更好的方法来做到这一点?例如
var gridHeader = $("#grid_GridHeader")[0];
回答by Nick Craver
You can use .get(0)as well but...you shouldn't need to do that with an element found by ID, that should alwaysbe 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(0),但是...您不需要使用 ID 找到的元素来执行此操作,该元素应该始终是唯一的。我希望这只是示例中的一个疏忽……如果您的实际页面是这种情况,您需要修复它以使您的 ID 是唯一的,并使用类(或其他属性)代替。
.get()(like [0]) gets the DOM element, if you want a jQuery object use .eq(0)or .first()instead :)
.get()(如[0])获取 DOM 元素,如果您想要使用 jQuery 对象,.eq(0)或者.first()改为 :)
回答by Mervyn
$("#grid_GridHeader:first")works as well.
$("#grid_GridHeader:first")也有效。
回答by Bennidhamma
You can use the first method:
您可以使用第一种方法:
$('li').first()
btw I agree with Nick Craver -- use document.getElementById()...
顺便说一句,我同意 Nick Craver 的观点——使用 document.getElementById()...
回答by Ken Redler
With the assumption that there's only one element:
假设只有一个元素:
$("#grid_GridHeader")[0]
$("#grid_GridHeader").get(0)
$("#grid_GridHeader").get()
...are all equivalent, returning the single underlying element.
...都是等价的,返回单个底层元素。
From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0]approach:
从 jQuery 源代码中,您可以看到get(0),在幕后,本质上与该[0]方法执行相同的操作:
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
回答by Matt
You can use the first selector.
您可以使用第一个选择器。
var header = $('.header:first')
回答by Adam
回答by hjijin
You can try like this:
yourArray.shift()
你可以这样试试:
yourArray.shift()

