我的目标是仅使用Javascript从头开始复制普通的jQuery每个类型函数。到目前为止,这是我的代码:
// 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]
如您所见,每个都显示为错误。我该怎么办呢?
答案 0 :(得分:4)
一个像这样工作的轻量级类:
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本身也使用它)并且在很多情况下都能很好地为你服务。
答案 1 :(得分:1)
这样的事情...... ??
function $(object) {
var obj = {
arr : document.querySelectorAll(object),
each : function(fun){
for (var i = 0; i < this.arr.length; i++) {
fun.call(this, this.arr[i]);
}
}
}
return obj;
}