本文實例講述了JavaScript使用鏈式方法封裝jQuery中CSS()方法。分享給大家供大家參考,具體如下:
主要思路就是:返回this對象,將所獲取的操作元素放入一個數組中。在原型中添加拓展方法
<html><head> <title></title></head><body> <div id="one">aa</div></body><script type="text/javascript">//封裝類似于JQuery的連綴/*思路:一個操作后再返回本來的對象this,將獲取的元素放入一個數組內部。通過原型添加方法;為了能在原型對象中添加方法;這個應該用函數來建立原型對象function Base(){ this.getId=function(id){ return this; } 使用的時候,需要new一個實例對象 var newBase=Base();}*/function Base(){ this.element=[]; //獲取ID this.getId=function(id){ //將所獲取的元素放入數組里面,返回當前對象 this.element.push(document.getElementById(id)) // return this.element.length return this } //獲取className,遍歷push this.getClass=function(name){ var names=document.getElementsByName(name); for( var i=0;i<names.length;i++){ this.element.push(names[i]) } return this; } //獲取tagName;遍歷push this.getTag=function(tags){ var tags=document.getElementsByTagName(tags); for(var i=0;i<tags.length;i++){ this.element.push(tags[i]) } return this; } }//通過原型添加方法:Base.prototype.css=function(attr,value){ //遍歷選取當前元素 for(var i=0;i<this.element.length;i++){ this.element[i].style[attr]=value; } return this;}var newBase= new Base();// alert(newBase.getId("one"))newBase.getId("one").css("background","red").css("color","blue").css("fontSize","60")</script></html>更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript頁面元素操作技巧總結》、《JavaScript事件相關操作與技巧大全》、《JavaScript操作DOM技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答