javascript jQuery - 等同于 each(),但对于单个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4856938/
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
jQuery - equivalent to each(), but for a single element
提问by Alex
What's the jQuery equivalent for each():
each() 的 jQuery 等价物是什么:
$(".element").each(function(){  
  // do stuff
});
when attaching a function to a single element, like #element?
将函数附加到单个元素时,例如#element?
采纳答案by user113716
You can always reference the jQuery object in a variable:
您始终可以在变量中引用 jQuery 对象:
var $el = $('#element');
...then manipulate it.
...然后操纵它。
$el.doSomething();          // call some jQuery methods from the cached object
$el.doSomethingElse();
If the reason you wanted .each()was to reference the DOM element as this, you don't really need the thiskeyword to do it, you can simply grab the DOM element out of the jQuery object.
如果您想要的原因.each()是将 DOM 元素引用为this,那么您实际上并不需要this关键字来执行此操作,您可以简单地从 jQuery 对象中获取 DOM 元素。
var element = $('#element')[0];       // both of these give you the DOM element
var element = $('#element').get(0);   //        at index 0
The two of these are equivalent, and will retrieve the DOM element that would be referenced as thisin the .each().
这两个是等效的,将检索将this在.each().
alert( element.tagName );  // alert the tagName property of the DOM element
alert( element.id );       // alert the ID property of the DOM element
I'd note that it isn't necessarily bad to use each to iterate over a single element.
我要注意的是,使用 each 来迭代单个元素不一定是坏事。
The benefits are that you have easy access to the DOM element, and you can do so in a new scope so you don't clutter the surrounding namespace with variables.
好处是您可以轻松访问 DOM 元素,并且您可以在新的作用域中访问,这样您就不会用变量混淆周围的命名空间。
There are other ways to accomplish this as well. Take this example:
还有其他方法可以实现这一点。拿这个例子:
(function( $ ) {
    // Inside here, "this" will refer to the DOM element,
    //    and the "$" parameter, will reference the jQuery library.
    alert( this.tagName );
    // Any variables you create inside will not pollute the surrounding 
    //     namespace.
    var someVariable = 'somevalue'; // is local to this function
}).call( $('#element')[0], jQuery );
回答by BoltClock
To directly answer your question, .each()operates normally on element sets of any size including 1.
要直接回答您的问题,.each()通常对包括 1 在内的任何大小的元素集进行操作。
You can also omit the .each()call completely and just call jQuery methods on $('#element'). Remember that you can chain most if not all jQuery method calls as they return the jQuery object. This even works on multiple elements for the matter, depending on what the methods do.
你也可以.each()完全省略调用,只调用 jQuery 方法$('#element')。请记住,您可以链接大多数(如果不是全部)jQuery 方法调用,因为它们返回 jQuery 对象。这甚至适用于该问题的多个元素,具体取决于方法的作用。
$('#element').doSomething().doSomethingElse();
If you need to reference the object multiple times, make a variable:
如果您需要多次引用该对象,请创建一个变量:
var $elm = $('#element');
$elm.doSomething();
doSomethingElse($elm);
回答by GolezTrol
Use first().
使用first().
each()matches all elements, while first()matches only the first. 
each()匹配所有元素,而first()只匹配第一个。
There are other selectors too. When you use the id in the selector, you will only get one element. This is the main difference between .elementand #element. The first is a class that can be assigned to many elements, while the second is an id that belongs to only (at most) one element.
还有其他选择器。当你在选择器中使用 id 时,你只会得到一个元素。这是.element和之间的主要区别#element。第一个是可以分配给许多元素的类,而第二个是只属于(最多)一个元素的 id。
You can still use each if only one (or 0) element is returned. Also, you can skip each altogether if you want to link an event. You use eachwhen you want to execute a specific function for each element in the list of elements.
如果只返回一个(或 0 个)元素,您仍然可以使用每个元素。此外,如果您想链接一个事件,您可以完全跳过每个。each当您要为元素列表中的每个元素执行特定功能时使用。
回答by zzzzBov
Behind the scenes, eachis just a forloop that iterates through each element in the mapreturned by jQuery.
在幕后,each只是一个for循环,它遍历map返回的 by中的每个元素jQuery。
It is essentially†the same as:
它本质上与以下†相同:
var i, map = $('...selector...');
for (i = 0; i < map.length; i++)
{
  someFunction(i, map[i]);
}
† There's more to it than this, involving calling the function in the context of the map element etc.
† 还有更多的东西,包括在地图元素等的上下文中调用函数。
It's implementation is to provide a convenient way to call a function on eachelement in the selection.
它的实现是提供一种方便的方法来调用each选择中元素的函数。
回答by John Cartwright
If there is only 1 element, you can access it normally using the selector.
如果只有 1 个元素,您可以使用选择器正常访问它。
$('#your_element').your_event(function() {
});
回答by Kai Qing
Do you mean like $('#element').children().each() supposing you have something like a ul with an id and you want the li each inside it?
你的意思是像 $('#element').children().each() 假设你有一个带有 id 的 ul 并且你想要每个里面的 li 吗?
回答by Flow
If the intention is to call a (non-jQuery) function in a new scope I think using "each" still is a valid (and probably the most elegant) way and it stays true to the jQuery syntax although I agree to Alex, it feels wrong since it might have some overhead.
If you can change the syntax use $('#element')[0]as replacement for this(as already mentioned in the accepted answer).
如果目的是在新的范围内调用(非 jQuery)函数,我认为使用“each”仍然是一种有效的(并且可能是最优雅的)方式,尽管我同意 Alex,但它仍然忠于 jQuery 语法,它感觉不对,因为它可能有一些开销。如果您可以更改语法使用$('#element')[0]作为替代this(如已接受的答案中所述)。
Btw could someone with enough reputation please correct the comment of "zzzzBov" about the accepted answer? 
$('#element')[0]and $('#element').get(0)ARE!the same, if you want the jQuery object use $('#element').first()or $('#element').eq(0)
顺便说一句,有足够声誉的人可以纠正“zzzzBov”关于已接受答案的评论吗? 
$('#element')[0]和$('#element').get(0)ARE!相同,如果您希望使用 jQuery 对象$('#element').first()或$('#element').eq(0)

