JavaScript使用鏈式方法封裝jQuery中CSS()方法示例
本文實例講述了JavaScript使用鏈式方法封裝jQuery中CSS()方法。分享給大家供大家參考,具體如下:
主要思路就是:返回this對象,將所獲取的操作元素放入一個數(shù)組中。在原型中添加拓展方法
<html>
<head>
<title></title>
</head>
<body>
<div id="one">aa</div>
</body>
<script type="text/javascript">
//封裝類似于JQuery的連綴
/*
思路:一個操作后再返回本來的對象this,將獲取的元素放入一個數(shù)組內(nèi)部。通過原型添加方法;
為了能在原型對象中添加方法;這個應該用函數(shù)來建立原型對象
function Base(){
this.getId=function(id){
return this;
}
使用的時候,需要new一個實例對象
var newBase=Base();
}
*/
function Base(){
this.element=[];
//獲取ID
this.getId=function(id){
//將所獲取的元素放入數(shù)組里面,返回當前對象
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相關內(nèi)容感興趣的讀者可查看本站專題:《JavaScript頁面元素操作技巧總結》、《JavaScript事件相關操作與技巧大全》、《JavaScript操作DOM技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數(shù)據(jù)結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數(shù)學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
寫入cookie的JavaScript代碼庫 cookieLibrary.js
cookieLibrary.js 寫入cookie的JavaScript代碼庫,需要的朋友可以參考下。2009-10-10
JS 組件系列之 bootstrap treegrid 組件封裝過程
最近產(chǎn)品需要設計一套相對完整的組織架構的解決方案,由于組織架構涉及到層級關系,在表格里面展示層級關系,自然就要用到所謂的treegrid。下面小編通過本文給大家分享JS 組件系列之 bootstrap treegrid 組件的封裝過程,需要的朋友可以參考下2017-04-04

