jQuery链函数如何在仍返回数组的同时? [英] How does jQuery chain functions while still returning an array?
问题描述
jQuery如何完成命令的链接?
和
jquery链接如何工作?
我仍然想知道在jQuery中如何实现这种功能
var a = $('body')
// a返回一个数组[< / body>< / body>]。
a.click()
//看起来像这样会返回一个错误,如果a返回一个数组而不是一个函数。
链接的SO答案只告诉我如何做一些事情,如$ / b
$ b
ab()。c()
这是 a()
我还是不明白。我知道链接通过返回这个
来工作,但它又如何自己返回一个数组?
使用jQuery源代码查看器网站的定义为$( http://james.padolsey.com/jquery/#v=1.9.1&fn= $)如下:
注意它从init()返回。 init内部( http://james.padolsey.com/jquery/ #v = 1.9.1& fn = init )我们看到最后它调用了一个名为makeArray的函数: init 这给我们带来了问题的答案'jQuery链接函数如何仍然返回数组?' makeArray( http://james.padolsey.com/jquery/#v=1.9.1&fn=jQuery.makeArray )如下所示:
$ p $ function(selector,context){
// jQuery对象实际上只是init构造函数'enhanced'
返回新的jQuery.fn.init(selector,context,rootjQuery);
function(selector,context,rootjQuery){
var match,elem;
//函数定义的其余部分
返回jQuery.makeArray(selector,this);
}
makeArray
函数(arr,results){
var ret = results || [];
if(arr!= null){
if(isArraylike(Object(arr))){
jQuery.merge(ret,typeof arr ===string? [arr]:arr);
} else {
core_push.call(ret,arr);
}
}
return ret;
}
Having read
How does jQuery accomplish chaining of commands? and how does jquery chaining work?
I am still left to wonder how something like this is possible in jQuery
var a = $('body')
// a returns [<body></body>], an array.
a.click()
// Seems like this should return an error if a returns an array, not a function.
The linked SO answers have only told me how to do things like
a.b().c()
It's the a()
I still don't understand. I understand that chaining works by returning this
but then how does it also return an array by itself?
Using the jQuery source code viewer site the definition for $ (http://james.padolsey.com/jquery/#v=1.9.1&fn=$) is as follows:
$
function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
}
Notice it is returning from init(). Inside of init (http://james.padolsey.com/jquery/#v=1.9.1&fn=init) we see that at the end it calls a function called makeArray:
init
function (selector, context, rootjQuery) {
var match, elem;
// rest of function defintion
return jQuery.makeArray(selector, this);
}
Which brings us to the answer to the question 'How does jQuery chain functions while still returning an array?'
makeArray (http://james.padolsey.com/jquery/#v=1.9.1&fn=jQuery.makeArray) looks like this:
makeArray
function (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
jQuery.merge(ret, typeof arr === "string" ? [arr] : arr);
} else {
core_push.call(ret, arr);
}
}
return ret;
}
这篇关于jQuery链函数如何在仍返回数组的同时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!