尝试从头开始使用Javascript创建each()类型的jQuery函数
我的目标是只使用Javascript从头开始复制普通的jQuery每种类型的函数。以下是我目前的代码:尝试从头开始使用Javascript创建each()类型的jQuery函数,javascript,jquery,Javascript,Jquery,我的目标是只使用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++) {
// 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]
//创建了一个类似jQuery的对象引用
函数$(对象){
返回单据.querySelectorAll(对象);
this.each=函数(){
对于(var j=0;j
正如您所看到的,每个都显示为一个错误。我该如何着手解决这个问题 像这样的东西
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;
}
函数$(对象){
var obj={
arr:document.queryselectoral(对象),
每个:功能(乐趣){
对于(var i=0;i
这样工作的轻量级类是:
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
我在这里使用的模式是众所周知的(事实上jQuery本身也使用它),在很多情况下都会为你服务。< /P>为什么要重新发明轮子?你在问什么吗?斯蒂奥:你认为什么是“jQuery选择器”?假设它是
$
,为什么不为一个将被重复使用的函数使用一个易于键入的短变量名呢?@Mohammad,我的Javascript课程有一个学校作业,我不允许使用jQuery,这就是为什么我试图创建自己的类似于jQuery的简单函数的原因。如果您不熟悉JavaScript,您可能会发现它很有用。那太好了!,很好用!问题:1。在$(选择器)函数中,第2行具体做什么?另外,您如何正确引用“this”?当我试图在函数中引用“this”时,它引用了index.html文件。2. $.原型,我很难掌握原型方法的概念。你能简单地解释一下它是如何工作的吗?非常好,解释得很好+1@ShivamBhalla当前位置请看我添加的内容。不同之处在于,您的代码在调用函数时没有使用new
。函数的第一行确保如果有人调用$(x)
而不是new$(x)
,我们正确地调用new$(x)
并返回该值。你必须使用new
使这个指向实例,否则你就会看到发生了什么。@ShivamBhalla:有很多材料可以回答你关于new
和JS中的对象原型的问题,比我在这里写的要多得多,也要好得多。例如,搜索SO和google,非常感谢您的帮助!这真的给了我工具来创造更多,并了解更多关于这些方法是如何工作的。无法解释这对我以后有多大帮助:)再次感谢!
$("div").each(function(index) { console.log(this); });