为什么jQuery的回调参数不一致? [英] Why are jQuery's callback arguments inconsistent?

查看:136
本文介绍了为什么jQuery的回调参数不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery的一个常见的​​模式是需要被传递一个数组的元素和数组中指数回调的方法。然而,似乎完全随机的哪个参数是第一位的。例如,从jQuery文档在 http://api.jquery.com

A common pattern within jQuery is a method that takes a callback which is passed an element of an array and its index within that array. However, it seems completely random which argument comes first. For example, from the jQuery docs at http://api.jquery.com:


  • jQuery.each(收集,回调(indexInArray,valueOfElement))

  • 。每个(函数(指数,元素))

  • jQuery.map(数组,回调(elementOfArray,indexInArray))

  • .MAP(回调(指标,一个DOMElement))

  • jQuery.grep(数组,函数(elementOfArray,indexInArray),[反转])

  • .filter(函数(指数))

  • jQuery.each( collection, callback(indexInArray, valueOfElement) )
  • .each( function(index, Element) )
  • jQuery.map( array, callback(elementOfArray, indexInArray) )
  • .map( callback(index, domElement) )
  • jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] )
  • .filter( function(index) )

在三起案件( jQuery.each 。每个 .MAP )的索引是第一位的。在另外两个( jQuery.grep jQuery.map )的元素是第一位的。我知道API现在已确定,但它似乎是一个矛盾总给我。

In three cases (jQuery.each, .each, .map) the index comes first. In the other two (jQuery.grep, jQuery.map) the element comes first. I know the api is now set, but it seems like a gross inconsistency to me.

有没有我缺少一个模式或者这只是随机的?如果这个问题能解决,或者我应该闭嘴,并记住他们?

Is there a pattern I'm missing or is this just random? Should this be fixed or should I just shut up and memorize them?

推荐答案

这不是完全随机的。这是因为:

It is not totally random. Because :

$.map( $('selector'), function(el, index) { /* element (DOMElement) is first, index optional */ } );
$('selector').map(function(index) { /* 'this' (DOMElement) is first.... index optional */ });

查看模式?第二个例子具有第二个参数,但它仅采用方便过去了,现在是一样的这个

See the pattern? The second example has a second argument, but it is only passed by convenience, and it is the same as this.

该模式是第一个参数总是比第二个更重要的是,最后一个参数应该是最重要的(以下简称更多的可选)。所以你并不需要,如果你只需要一个指定所有最不重要的参数。而在 $的情况下,(...)。每个,往往你甚至不需要任何参数,因为这个仅仅是你想要的。

The pattern is that the first argument is always "more" important than the second, and the last argument should be the least important (the "more optional"). So you don't need to specify all the least important arguments if you only need one. And in the case of $(...).each, often you won't even need any argument, because this is only what you want.

这篇关于为什么jQuery的回调参数不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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