仿造jQuery寫一個簡單的框架,體驗框架的快感
javascprit部分
<script>
function $$(support){
if(typeof support != "function"){
console.info("傳入的參數不是函數")
}else{
var doc = window.document;
//谷歌和火狐瀏覽器
if(doc.addEventListener){
doc.addEventListener("DOMContentLoaded",support,false);
}else{//IE
//監聽文檔事件
doc.onreadystatechange = function(){
//IE6 || IE7 || IE8
if(doc.readyState == "loader" || doc.readyState == "complete" || doc.readyState == "interactive"){
support();
}
}
}
}
}
(function(window){
//公共方法,讓別人去調用
window.$=function(selector){
return new jQuery(selector);
}
//私有的對象
var jQuery = function(selector){
//給jQuery對象綁定數組用來存放獲取的元素
this.box = document.querySelectorAll(selector);
}
//重新定義jQuery類函數的prototype
jQuery.prototype={
//innerText方法
text:function(value){
for (var i = 0; i < this.box.length; i++) {
//把傳入的值寫到HTML
this.box[i].innerText = value;
}
return this;//返回this可以鏈式編程
},
//css方法
css:function(key,value){
for (var i = 0; i < this.box.length; i++) {
//把傳入的值放到style
this.box[i].style[key]=value;
}
return this;//返回this可以鏈式編程
}
}
})(window);
//調用框架
$$(function(){
$("#box1").text("Hello world!").css("color","lightgreen").css("font-size","100px").css("text-align","center").css("height","100%");
$("#box2").text("Hello JAVAScript!").css("color","blue").css("font-size","100px").css("text-align","center").css("height","100%");
});
</script>
html部分
<html>
<head>
</head>
<body>
<div id="box1" style="background-color:black;height:50px"></div>
<div id="box2" style="background-color:orange;height:50px"></div>
</body>
</html>