尝试从头开始使用Javascript创建each()类型的jQuery函数 [英] Attempt to create a each() type jQuery function using Javascript from scratch

查看:61
本文介绍了尝试从头开始使用Javascript创建each()类型的jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是仅使用Javascript从头开始复制普通的jQuery每个类型函数。这是我到目前为止的代码:

My goal is to replicate the normal jQuery each type function from scratch using only Javascript. Here is my code so far:

// Created a jQuery like object reference
function $(object) {
    return document.querySelectorAll(object);

    this.each = function() {
        for (var j = 0; j < object.length; j++) {
            return object[j];
        }
    }

}

console.log($('.dd')); // returns NodeList[li.dd, li.dd]

$('.opened').each(function() {
    console.log(this);
}); // Results in an error [TypeError: $(...).each is not a function]

正如您所看到的,每个都显示为错误。我该怎么办呢?

As you can see, each is showing as a error. How should I go about fixing this?

推荐答案

一个像这样工作的轻量级类:

A lightweight class that works like that would be:

function $(selector) { 
    // This function is a constructor, i.e. mean to be called like x = new $(...)
    // We use the standard "forgot constructor" trick to provide the same
    // results even if it's called without "new"
    if (!(this instanceof $)) return new $(selector);

    // Assign some public properties on the object
    this.selector = selector;
    this.nodes = document.querySelectorAll(selector);
}

// Provide an .each function on the object's prototype (helps a lot if you are
// going to be creating lots of these objects).
$.prototype.each = function(callback) {
    for(var i = 0; i < this.nodes.length; ++i) {
        callback.call(this.nodes[i], i);
    }
    return this; // to allow chaining like jQuery does
}

// You can also define any other helper methods you want on $.prototype

您可以这样使用:

$("div").each(function(index) { console.log(this); });

我在这里使用的模式是众所周知的(实际上jQuery本身也使用它)并且将会在很多情况下为你提供良好的服务。

The pattern I 've used here is widely known (in fact jQuery itself also uses it) and will serve you well in a great many cases.

这篇关于尝试从头开始使用Javascript创建each()类型的jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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