2015-09-06 103 views
0

需要帮助。我有一个名为Rigged的库,类似于jQuery。 此代码是不完整的,这只是我的代码示例(我的lib中拥有超过500线尚)在同一对象中使用对象的方法

(function() { 
    var arr = []; 
    var Rigged = function (selector) { 
      return Rigged.fn.init(selector); 
    }; 

    Rigged.fn = Rigged.prototype = { 
      map: function (callback) { 
        var results = arr, i = 0; 
        for (; i < this.length; i++) { 
         results.push(callback.call(this, this[i], i)); 
        } 
        return results; 
      }, 

      each: function (callback) { 
       return this.map(callback); 
      }, 

      // this is just example of my code 
      css: function (attr, value) { 
       if (attr == 'display') { 
         return this.each(function (current) { 
           current.style.display = value; 
         }); 
       } 
      }, 

      hide: function() { 
       return this.each(function (current) { 
         // here's a problem 
         current.css('display', 'none'); 
       }); 
      } 

    }; 


    Rigged.init = Rigged.fn.init = function (selector) { 
      var elset, i = 0; 
      if (typeof selector === "string") 
       elset = document.querySelectorAll(selector); 
      else if (...) 
       .... etc 

      this.length = elset.length; 
      for (; i < this.length; i++) { this[i] = elset[i]; } 
      return this; 
    } 

    Rigged.ajax = Rigged.fn.ajax = function (obj) { 
      // code here 
    } 

    window.Rigged = window.$ = Rigged; 
}()); 

所以,我有打电话map方法或each没有问题,但在方法的定义,所谓hide它打印一个错误Uncaught TypeError:current.css不是控制台中的函数

当我在$("#text").css('display', 'none);这样的索引文件中调用css时,它有效,但在Rigged.prototype中不起作用。当我将current.css('display', 'none');替换为current.style.display = 'none';时,它正常工作。

有谁能告诉我为什么.css方法不起作用吗?

EDITED .MAP()方法 + E(回调)到当前

回答

0

这里是溶液。

 hide: function() { 
      // Try to log `this` 
      console.log(this); 

      /*return this.each(function (current) { 
       current.css('display', 'none'); 
      });*/ 

      this.css('display', 'none'); 
     } 

您正在运行.each()两次,当你调用.hide()。其中一个在.hide()之内,第二个在.css()之内,这就是问题所在。

+0

那么'.map'方法错了?我无法使用它?我是否应该只在其他方法中使用'this'? – Peter

+0

@Peter'.map()'没有错,但我认为没有必要使用它,它只是加载一个循环。 '.each()'就足够你的目的。 – thecodeparadox

+0

好的..非常感谢 – Peter

0

您正在向对象添加DOM节点,而不是类似jQuery的对象,dom节点。

当你映射每个元素,你通过DOM元素回调函数:

results.push(callback.call(this, this[i], i)); 
//-------------------------------^^^^^^^ here 

当你

current.css('display', 'none'); 

在你.hide()方法,你想在一个没有这种方法的DOM元素上调用.css(),所以你得到一个错误。

+0

但是它有什么问题?我在调用.map()时没有问题。你能告诉我应该如何替换它? – Peter

+0

我认为不是。你能告诉我如何解决它吗?当我从开始时得知它是错误的时候,我非常反感 – Peter

+0

请参阅[codeparadox答案。](http://stackoverflow.com/a/32427714/1612146) – George