// 避免變數的全域污染
(function(){
/* jQuery 建構式 */
function jQuery(selector){
return new jQuery.fn.init(selector);
// 回傳 init 建構式創造的實體
}
// 原型起個別名
jQuery.fn = jQuery.prototype;
/* init 初始化方法 */
jQuery.fn.init = function(selector){
if(typeof selector == 'object'){
this[0] = selector;
this.length = 1;
// 如果傳入的是物件,就把物件當this里面的元素
}else if(typeof selector == 'function'){ //當selector是函式時候 執行ready方法
jQuery.fn.ready(selector);
}else{
var elems = document.querySelectorAll(selector);
// 選擇到所有的元素
for(var i=0;i<elems.length;i++){
this[i] = elems[i];
}
// 變數把選擇到的物件掛載到實體上
this.length = elems.length;
// 設定長度
return this; //回傳 init創造的實體
}
}
/* dom操作方法 */
/* each 遍歷方法:變數this指向回呼函式fn */
jQuery.fn.each = function(fn){
for(var i=0;i<this.length;i++){
fn(this[i]);
}
return this;
}
/* on方法 系結事件 */
jQuery.fn.on=function(type,fn){
this.each(function(elem){
elem.addEventListener(type,fn);
})
return this;
}
/* toggleClass方法 */
jQuery.fn.toggleClass=function(name){
this.each(function(elem){
elem.classList.toggle(name)
})
return this;
}
jQuery.fn.toggle=function(name){
this.each(function(elem){
var display = document.defaultView.getComputedStyle(elem,null).display;
// 檔案.默認視圖,獲取電腦計算的樣式(元素,null)
// 獲取瀏覽器計算過后元素的css屬性
if(display!='none'){ //如果得到display值不是none
elem.oldview = display; //用oldview 屬性記錄下
elem.style.display = 'none'; //隱藏
}else{
elem.style.display = elem.oldview||'block';
// 否則 顯示
}
})
return this;
}
/* 實作ready方法 */
jQuery.fn.ready = function(callback){
if(jQuery.isReady){
callback();
}else{
setTimeout(()=>{
jQuery.fn.ready(callback);
},10)
}
// 如果jquery 準備好了執行 callback
}
document.addEventListener("DOMContentLoaded",e=>jQuery.isReady=true);
// 檔案加載完畢設定jQuery的isReady為true
jQuery.fn.init.prototype = jQuery.prototype;
// 重新指向prototype;(為了讓實體擁有jQuery prototype上面的公用方法)
// 全域掛載
window.$ = window.jQuery = jQuery;
})()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jquery</title>
<script src="js/jquery-5.0.js"></script>
<style>
.active{color:red;}
</style>
</head>
<body>
<button>切換</button>
<h1> 我愛<span>我的</span>祖國</h1>
<p>我喜歡jquery</p>
<p>我愛vue</p>
<script>
// console.log($);
// console.log(jQuery);
// $("p").on("click",function(){
// $(this).toggleClass("active");
// })
// $("button").on("click",function(){
// $("span").toggle();
// })
$(function(){
// alert("檔案加載完畢")
console.log("檔案加載完畢")
})
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/82750.html
標籤:其他
上一篇:FPGA——數字電路崛起的新星
下一篇:js面試題中的異步問題
