Javascript jquery的微型实现

Javascript jquery的微型实现,javascript,jquery,this,each,Javascript,Jquery,This,Each,1) 我的任务是在Javascript上实现jQuery。 但由于某种原因,我的方法每一种都不起作用。 比如当我写作的时候 $('.a').each(function (index) {$(this).append('<b>' + index + '</b>')}) $('#id').each(function (index) {$(this).html('<b>' + index + '</b>')}) 比如当我写作的时候 $('.a').

1) 我的任务是在Javascript上实现jQuery。 但由于某种原因,我的方法每一种都不起作用。 比如当我写作的时候

$('.a').each(function (index) {$(this).append('<b>' + index + '</b>')})
$('#id').each(function (index) {$(this).html('<b>' + index + '</b>')})

比如当我写作的时候

$('.a').each(function (index) {$(this).append('<b>' + index + '</b>')})
$('#id').each(function (index) {$(this).html('<b>' + index + '</b>')})

但是,除此之外,您还将遇到许多其他问题,您需要调试器来解决这些问题。

这将适用于您的用例,但要实现所有边缘情况将有点复杂:

(function() {
  function $(selector) {
    if (!(this instanceof $)){//forgot new
      return new $(selector);
    }
    if(typeof selector === 'string'){ 
      return this.search(selector);
    }
    //assuming selector is a dom object
    this[0]=selector;
    this.length=1;
  }
  $.prototype = {
    constructor: $,
    length: 0,

    search: function(selector) {
      var that=this;
      var elems=Array.prototype.slice
          .call(document.querySelectorAll(selector));
      elems.forEach(function(x,i){that[i]=x;});
      this.length = elems.length;
      return this;
    },
    append: function(text) {
      if (text instanceof $) {
        this[0].appendChild(text[0]);
        for(var i = 1; i < this.length-1; i++) {
          var p = text[0].cloneNode(true);
          this[i].appendChild(p);
        }
      } else {
           this.each(function(x){
              this.innerHTML  =  this.innerHTML  +  text;
          });
      }
      return this;
    },  
    // callback is called with the invoking object to be the dom element
    each: function(callback){
      for (var i=0;i<this.length;i++){
        this[i]=callback.call(this[i],i);
      };
      return this;
    },

  }
  window.$ = $;
}());
$('.a').each(function (index) {return $(this).append('<b>' + index + '</b>')})
(函数(){
函数$(选择器){
如果(!(此实例为$){//new
返回新的$(选择器);
}
如果(选择器的类型=='string'){
返回此.search(选择器);
}
//假设选择器是dom对象
此[0]=选择器;
这个。长度=1;
}
$.prototype={
构造函数:$,
长度:0,
搜索:功能(选择器){
var=这个;
var elems=Array.prototype.slice
.call(document.queryselectoral(选择器));
forEach(函数(x,i){that[i]=x;});
this.length=elems.length;
归还这个;
},
附加:函数(文本){
if(文本实例of$){
此[0]。追加子项(文本[0]);
for(var i=1;i对于(var i=0;i“我有一项任务要在Javascript上实现jQuery。”呃……jQuery是在Javascript上实现的。它在fiddle上工作,顺便说一下,供参考,在选择器上使用
。each()
方法选择
#id
(这是单个元素)没有任何意义。好的,我已经更正了在类中使用它。但是意义是一样的。我不能使用$(这个)和这个。每个方法在其他方法中都不起作用。@ozil:你在其中使用的是真正的jQuery。OP正在尝试重新实现jQuery,(开始)关于问题中的代码。我不明白为什么当我在一个附加函数之外时,这看起来没问题,但下一步是每个函数,现在这个[0]没有定义。我明白了!我的每个函数都写得不对!我还有一个问题!当我写.children()时函数我希望“this”被更改并返回它。我删除所有属性:0,1,2…直到“this”中的长度,然后用新的属性替换它们,这是它的子属性,对吗?或者有更优雅的方法来执行此操作?您的答案非常有帮助,但是每个函数都应该更改,以便只调用回调而不分配它与此[我]