2015-09-06 102 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