2016-02-23 72 views
3

我有用OOP方式創建next()函數的問題。Javascript創建下一個()函數OOP方式

這是小提琴:https://jsfiddle.net/s5e1530c/

"use strict"; 

var i, j, arr, loop, $; 

(function() { 

    $ = function(el, context) { 
     context = context || document; 
     return new obj$(el, context); 
    }; 

    var obj$ = function(el, context) { 

     if (context == null) { 
      var cl = context.getElementsByClassName(el), 
       loop = cl.length; 

      this.length = loop; 

      for (i = 0; i < loop; i++) { 
       this[i] = cl[i]; 
      } 

     } 
     else { 
      var cl = context, 
       loop = cl.length; 

      this.length = loop; 

      for (i = 0; i < loop; i++) { 
       this[i] = cl[i]; 
      } 

     } 


     return this; 

    }; 

    obj$.prototype = { 

     next : function() { 

     if (this.length == 1) { 

      return $(this[0], this[0].nextElementSibling); 

     } 

     return $(); 

     }, 
     css : function(obj, data) { 

      if (this.length == 1) { 
       this[0].style[obj] = data; 

      } 

      return this; 

     } 
    }; 

})(); 

<div class="child">child</div> 
<div class="next">Next</div> 

var child  = $("child"), 
    nextchild = child.next(); 

nextchild.css("color", "red"); 

爲什麼這個代碼不工作?控制檯上沒有錯誤。

我的代碼有什麼問題?

在此先感謝......

+0

很多問題,我沒有爲你做所有的工作,所以去一個頭,看看我離開了。 – EasyBB

回答

0
(function() { 
"use strict"; 

    var i, j, arr, loop, $, Obj$; 

$ = function(el, context) { 
    context = context || document; 
    return new Obj$(el, context); 
}; 

Obj$ = function(el, context) { 

    if(typeof el == "object") { 

    //take care of objects here 


    } 
    /* 
    why would context be null? It's either context or document 
    if (context == null) { 
     var cl = context.getElementsByClassName(el), 
      loop = cl.length; 

     this.length = loop; 

     for (i = 0; i < loop; i++) { 
      this[i] = cl[i]; 
     } 

    } 
    else { 
    */ 
     var cl = context.getElementsByClassName(el), 
      loop = cl.length; 

     this.length = loop; 

     for (i = 0; i < loop; i++) { 
      this[i] = cl[i]; 
     } 

    //} 


    return this; 

}; 

Obj$.prototype = { 

    next : function() { 
    //why do equals 1? Do greater than or equal to 1 
    if (this.length >= 1) { 
     return $(this[0].nextElementSibling); 

    } 
    //return undefiend not an empty object 
    return undefined; 

    }, 
    css : function(obj, data) { 

     if (this.length >= 1) { 
      this[0].style[obj] = data; 
     } 

     return this; 

    } 
}; 

window.$ = $; 
})(); 

var child = $("child"), 
nextchild = child.next(); 

nextchild.css("color", "red"); 

你有很多工作要做,以得到你的工作,你想要的方式。對於你的選擇過程非常微弱,你對長度和對象的理解也非常弱。