当返回jQuery对象数组时,jQuery如何调用对象的方法? [英] How does jQuery invoke methods of objects when an Array of jQuery objects is returned?

查看:171
本文介绍了当返回jQuery对象数组时,jQuery如何调用对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字符串选择器"传递给jQuery函数后:

After passing a string "selector" into the jQuery function:

$('#onenode')

返回jQuery对象的数组.

An array of jQuery object's is returned.

这些对象的方法之一是"html",这就是原因:

One of the methods of these object's is "html", which is why:

$('#onenode').html('hello!');

工作.

但是...

此:

$('.somenodes')

返回一个jQuery对象数组,此数组中的每个对象都有方法"html".

Returns an array of jQuery objects, each of the objects in this array has the method "html".

那怎么做:

$('.somenodes').html('hello');

工作吗? "html"方法必须是返回的数组对象的方法.

Work? The "html" method must be a method of the Array Object that is returned.

因此,我假设数组对象的"html"方法看起来与此类似:

I assume therefore that the "html" method of the Array Object looks similar to this:

html: function(value) {
   for(var i=0; i<this.length; i+=1) {
      this[i].html(value);
   }
}

这些都是假设,我几乎是在猜测.

These are all assumptions, I'm pretty much guessing.

我正在尝试创建自己的使用选择器"的小型库,但是我在这一部分上苦苦挣扎.我知道这可能是错误的-有人可以解释jQuery的实际作用吗?

推荐答案

jQuery基本上是一个很大的prototype,带有一堆return this方法,其中this是您正在使用的jQuery实例.

jQuery is basically a big prototype with a bunch of methods that return this, where this is the instance of jQuery you're working with.

我正在尝试创建自己的使用选择器"的小型库

I am attempting to create my own small library that uses "selectors"

这是在现代浏览器中工作的类似jQuery的模式的简化示例:

Here's a very reduced example of a jQuery-like pattern that works in modern browsers:

(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完全相同:

You can use that to build your jQuery like library. It works exactly like jQuery:

$('p').each(function() {
  console.log(this);
});

一个开始运行的函数,即eachmap.这些是jQuery到处使用的用于操纵DOM元素的方法. this.el是元素数组,而this是jQuery实例.只是不要忘记,在每个将要链接的方法中都需要return this.

A currying function, each and map is all you need to get started. Those are the methods the jQuery uses pretty much everywhere to manipulate DOM elements. this.el is the array of elements while this is the jQuery instance. Just don't forget that you need to return this in every method that will be chained.

这篇关于当返回jQuery对象数组时,jQuery如何调用对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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