当返回一个jQuery对象数组时,jQuery如何调用对象的方法?
将字符串“selector”传递给jQuery函数后:
$('#onenode')
返回一个jQuery对象数组。
这些对象的方法之一是“html”,这就是为什么:
$('#onenode').html('hello!');
作品。
然而…
这个:
$('.somenodes')
返回一个jQuery对象数组,该数组中的每个对象都有方法“html”。
那怎么做:
$('.somenodes').html('hello');
工作? “html”方法必须是返回的Array对象的方法。
因此我假设Array对象的“html”方法看起来类似于:
html: function(value) { for(var i=0; i<this.length; i+=1) { this[i].html(value); } }
这些都是假设,我猜很多。
我正在尝试创建自己的小库,使用“选择器”,但我正在努力解决这个问题。 我知道这可能是错误的 – 有人可以解释一下jQuery是如何做到的吗?
jQuery基本上是一个大型prototype
,有很多方法可以return this
, this
是你正在使用的jQuery实例。
我正在尝试创建自己的小库,使用“选择器”
这是一个非常简化的类似jQuery的模式示例,适用于现代浏览器:
(function(win, doc) { var __slice = [].slice; function jQuery(selector) { this.el = this._init(selector); this.length = this.el.length; } function $(selector) { return new jQuery(selector); } jQuery.prototype = { _init: function(selector) { return __slice.call(doc.querySelectorAll(selector)); }, each: function(fn) { return this.el.some(fn), this; }, map: function(fn) { return this.el.map(fn), this; } }; win.$ = $; }(window, document));
您可以使用它来构建类似jQuery的库。 它的工作方式与jQuery完全相同:
$('p').each(function() { console.log(this); });
一个currying函数, each
和map
都是你需要开始的。 这些是jQuery几乎在任何地方用来操作DOM元素的方法。 this.el
是元素数组,而this
是jQuery实例。 只是不要忘记你需要在每个被链接的方法中return this
。
$('.somenodes')
不返回数组,它只是一个jquery对象,它有一些本机数组的函数。
一段时间我也有类似的疑问,请在我的问题上查看这个答案.. https://stackoverflow.com/a/11158649/1114536
jQuery对象目前支持3种数组方法:
var methods = 'pop push reverse shift sort splice unshift concat join slice toString indexOf lastIndexOf filter forEach every map some reduce reduceRight'.split(' ') var implemented = $.grep(methods, function(m) { return $.prototype[m] == Array.prototype[m]; }); console.log(implemented); // => ["push", "sort", "splice"]
它们也有切片,但它与数组的切片不同:
$.prototype.slice === Array.prototype.slice // => false