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

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

问题描述

jQuery 中的一个常见模式是一个方法,它接受一个回调,该回调传递一个数组元素及其在该数组中的索引.但是,哪个参数先出现似乎完全随机.例如,来自 http://api.jquery.com 的 jQuery 文档:

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( 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.each.map)索引排在第一位.在另外两个(jQuery.grepjQuery.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 */ });

看到图案了吗?第二个例子有第二个参数,但只是为了方便传递,和this一样.

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

模式是第一个参数总是比第二个更"重要,最后一个参数应该是最不重要的(更可选").因此,如果您只需要一个参数,则无需指定所有最不重要的参数.而在 $(...).each 的情况下,通常你甚至不需要任何参数,因为 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天全站免登陆