js實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法與鏈?zhǔn)讲僮髟斀?/h1>
更新時(shí)間:2021年03月18日 10:58:11 作者:李不要熬夜
這篇文章主要給大家介紹了關(guān)于js實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法與鏈?zhǔn)讲僮鞯南嚓P(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
我用這篇文章來(lái)理一理如何用js去實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法。
本文js實(shí)現(xiàn)了下面jquery的幾種方法,我將它分為8個(gè)小目標(biāo)
- 實(shí)現(xiàn)$(".box1").click( )方法
- 實(shí)現(xiàn)$("div").click( )方法
- 考慮$( )中參數(shù)的三種情況
- 實(shí)現(xiàn)jq中的on方法
- 實(shí)現(xiàn)鏈?zhǔn)讲僮?/li>
- 實(shí)現(xiàn)jq中的eq方法
- 實(shí)現(xiàn)jq中的end方法
- 實(shí)現(xiàn)jq中的css方法
有不正確的地方還望大家在評(píng)論區(qū)指出來(lái),謝謝啦。
1. 實(shí)現(xiàn)$(".box1").click( )方法
首先,我們定第一個(gè)小目標(biāo),就是如何一步一步去實(shí)現(xiàn)下方j(luò)Query代碼的功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
//同一個(gè)文件下操作的話,后面記得刪除下面引入的cdn
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<style> .box1 {
width: 100px;
height: 100px;
background: red;
} </style>
</head>
<body>
<div class="box1"></div>
</body>
<script> $(".box1").click(()=>{
console.log(456);
}) </script>
</html>
復(fù)制代碼
$(".box1").click(()=>{
console.log(456);
})
好了,言歸正傳,我們來(lái)分析上面jQuery的代碼。
- $(".box1") 就是實(shí)現(xiàn)了選擇器的功能。
- $(".box1").click 就是選擇器 + 調(diào)用click方法
- 最后在click里面?zhèn)魅牒瘮?shù)。
第一個(gè)小目標(biāo)就是自己封裝js來(lái)實(shí)現(xiàn)上面代碼的功能。我們分三步走戰(zhàn)略來(lái)實(shí)現(xiàn)。
- js實(shí)現(xiàn) $(".box1")
- 實(shí)現(xiàn) $(".box1").click()
- 實(shí)現(xiàn) $(".box1").click( ( ) => { console.log("123") } )
第一步就是先用js實(shí)現(xiàn) $(".box1"), 對(duì)吧
// 實(shí)現(xiàn)$(".box1")
class jquery {
constructor(arg) {
console.log(document.querySelector(arg));
}
}
function $(arg) {
return new jquery(arg);
}
// 實(shí)現(xiàn)$(".box1")
let res = $(".box1");
console.log(res);
這樣是不是就通過(guò)構(gòu)建()方法并返回jquery實(shí)例,實(shí)現(xiàn)了(".box1")呢。
那好,接下來(lái)我們進(jìn)行第二步就是實(shí)現(xiàn) $(".box1").click()。相信大家也看出來(lái)了,就是在jquery類中多了一個(gè)click方法。
// 實(shí)現(xiàn)$(".box1").click()
class jquery {
constructor(arg) {
console.log(document.querySelector(arg));
}
click() {
console.log("執(zhí)行了click方法");
}
}
function $(arg) {
return new jquery(arg);
}
// 實(shí)現(xiàn)$(".box1").click()
let res = $(".box1").click();
console.log(res);
接下來(lái),我們進(jìn)行第三步就是實(shí)現(xiàn) $(".box1").click( ( ) => { console.log("123") } )。
// 實(shí)現(xiàn)$(".box1").click(() => {console.log("123")})
class jquery {
constructor(arg) {
this.element = document.querySelector(arg);
// console.log(element);
}
click(fn) {
this.element.addEventListener("click", fn);
}
}
function $(arg) {
return new jquery(arg);
}
//實(shí)現(xiàn)$(".box1").click(() => {console.log("123")})
$(".box1").click(() => {
console.log("123")
});
到此為止,我們實(shí)現(xiàn)了第一個(gè)小目標(biāo),大家是不是覺(jué)得簡(jiǎn)單呢,ok,接下來(lái)我們繼續(xù)第二個(gè)小目標(biāo)。
2. 實(shí)現(xiàn)$("div").click( )方法
第二個(gè)小目標(biāo)也不難,就是考慮有多個(gè)div元素需要綁定click事件,我們用selectSelectorAll來(lái)獲取元素的話,如何處理,其實(shí)也挺簡(jiǎn)單,就是在click方法中多出一個(gè)循環(huán),去獲取NodeList中的值。我直接上代碼了,大家試一試就知道啦。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> .box1 {
width: 100px;
height: 100px;
background: red;
}
.box2 {
width: 100px;
height: 100px;
background: blue;
} </style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
<script> // 實(shí)現(xiàn)$(".box1").click(() => {console.log("123")})
class jquery {
constructor(arg) {
//下面element存的是NodeList對(duì)象,它是一個(gè)類數(shù)組有l(wèi)ength屬性
this.element = document.querySelectorAll(arg);
}
click(fn) {
for(let i = 0; i < this.element.length; i++) {
this.element[i].addEventListener("click", fn);
}
}
}
function $(arg) {
return new jquery(arg);
}
//實(shí)現(xiàn)$(".box1").click(() => {console.log("123")})
$("div").click(() => {
console.log("123")
}); </script>
</html>
好了,完成兩個(gè)小目標(biāo)了,相信你已經(jīng)有成就感了。
3. 考慮$( )中參數(shù)的三種情況
接下來(lái)第三個(gè)小目標(biāo) 我們來(lái)考慮一下$( )中參數(shù)不同的情況,我先將三種情況列出來(lái)。(可能還有其他情況,這里就不說(shuō)了)
1.情況一:就是$( )參數(shù)為字符串
$(".box1")
2.情況二:就是$( )參數(shù)為函數(shù)的情況。
//參數(shù)為函數(shù)
$(function() {
console.log("123");
})
3.情況三:就是$( )參數(shù)為NodeList對(duì)象或selectSelect獲得的節(jié)點(diǎn)
// 情況三
$(document.querySelectorAll("div")).click(()=>{
console.log("123");
})
$(document.querySelector("div")).click(()=>{
console.log("456");
})
接下來(lái)第三個(gè)小目標(biāo)是手寫函數(shù)來(lái)實(shí)現(xiàn)三種情況。 首先我們?cè)黾觓ddEles方法,修改上面的click方法
addEles(eles){
for (let i = 0; i < eles.length; i++) {
this[i] = eles[i];
}
this.length = eles.length;
}
// 實(shí)現(xiàn)$(".box1").click(() => {console.log("123")})
click(fn) {
for(let i = 0; i < this.length; i++) {
this[i].addEventListener("click", fn);
}
}
接下來(lái)實(shí)現(xiàn)三種不同參數(shù)的處理方法
constructor(arg) {
//情況一
if(typeof arg === 'string') {
this.addEles(document.querySelectorAll(arg));
}else if(typeof arg === 'function') {
//情況二
document.addEventListener("DOMContentLoaded", arg);
}else {
//情況三
if(typeof arg.length === 'undefined') {
this[0] = arg;
this.length = 1;
}else {
this.addEles(arg);
}
}
}
4. 實(shí)現(xiàn)jq中的on方法
接下來(lái)實(shí)現(xiàn)第四個(gè)小目標(biāo) 實(shí)現(xiàn)jq的on方法
// on方法
on(eventName, fn) {
let eventArray = eventName.split(" ");
//考慮多個(gè)節(jié)點(diǎn)
for(let i = 0; i < this.length; i++) {
//考慮多個(gè)事件
for(let j = 0; j < eventArray.length; j++) {
this[i].addEventListener(eventArray[j], fn);
}
}
}
再測(cè)試下ok不
// on方法
$("div").on("mouseover mousedown",function(){
console.log("on方法");
})
5. 實(shí)現(xiàn)鏈?zhǔn)讲僮?br />
接下來(lái)實(shí)現(xiàn)第五個(gè)小目標(biāo) 實(shí)現(xiàn)jq的鏈?zhǔn)讲僮?/p>
劃重點(diǎn),在on和click中添加return this即可實(shí)現(xiàn)鏈?zhǔn)?/p>
//鏈?zhǔn)讲僮?
//劃重點(diǎn),在on和click中添加return this即可實(shí)現(xiàn)鏈?zhǔn)?
// click方法
click(fn) {
for(let i = 0; i < this.length; i++) {
this[i].addEventListener("click", fn);
}
return this;
// console.log(this);
}
// on方法
on(eventName, fn) {
let eventArray = eventName.split(" ");
//考慮多個(gè)節(jié)點(diǎn)
for(let i = 0; i < this.length; i++) {
//考慮多個(gè)事件
for(let j = 0; j < eventArray.length; j++) {
this[i].addEventListener(eventArray[j], fn);
}
}
return this;
}
6. 實(shí)現(xiàn)jq中的eq方法
接下來(lái)實(shí)現(xiàn)第六個(gè)小目標(biāo) 實(shí)現(xiàn)jq中的eq方法
//eq方法
eq(index) {
return new jquery(this[index]);
}
這里通過(guò)new一個(gè)jquery實(shí)現(xiàn) new的過(guò)程大家應(yīng)該清楚吧,我們溫習(xí)一下:
- 執(zhí)行函數(shù)
- 自動(dòng)創(chuàng)建一個(gè)空對(duì)象
- 將空對(duì)象的原型指向構(gòu)造函數(shù)的prototype屬性
- 將空對(duì)象和函數(shù)內(nèi)部this綁定
- 如果renturn后跟著對(duì)象,返回這個(gè)對(duì)象。沒(méi)跟的話就自動(dòng)返回this對(duì)象
7. 實(shí)現(xiàn)jq中的end方法
實(shí)現(xiàn)第七個(gè)小目標(biāo) 實(shí)現(xiàn)jq中的end方法。要實(shí)現(xiàn)這個(gè)功能,除了新增end( )方法,我們還得在構(gòu)造函數(shù)上實(shí)現(xiàn),constructor新增參數(shù)root,新增屬性prevObject,并在eq方法這種新增參數(shù)this。
constructor(arg, root) {
if(typeof root === "undefined") {
this.prevObject = [document];
}else {
this.prevObject = root;
}
//eq方法
eq(index) {
return new jquery(this[index], this);
}
//end方法
end() {
return this.prevObject;
}
8. 實(shí)現(xiàn)jq中的css方法
在jq中css可以獲取樣式,設(shè)置一個(gè)樣式或多個(gè)樣式
// 情況一 :獲取樣式 (只去獲取第一個(gè)元素)
let res = $("div").css("background");
console.log(res);
// 情況二 (設(shè)置樣式)
$("div").css("background","yellow");
// // 情況三 (設(shè)置多個(gè)樣式)
$("div").css({background:"black",width:200,opacity:0.3});
接下來(lái)實(shí)現(xiàn)css方法
//css方法
css(...args) {
if(args.length === 1) {
//情況一:獲取樣式
if(typeof args[0] === 'string') {
return this.getStyle(this[0], args[0]);
}else {
//情況三:設(shè)置多個(gè)樣式
for(let i = 0; i < this.length; i++) {
for(let j in args[0]) {
this.setStyle(this[i], j, args[0][j]);
}
}
}
}else {
//情況三
for(let i = 0; i < this.length; i++) {
this.setStyle(this[i], args[0], args[1]);
}
}
} //css方法
css(...args) {
if(args.length === 1) {
//情況一:獲取樣式
if(typeof args[0] === 'string') {
return this.getStyle(this[0], args[0]);
}else {
//情況三:設(shè)置多個(gè)樣式
for(let i = 0; i < this.length; i++) {
for(let j in args[0]) {
this.setStyle(this[i], j, args[0][j]);
}
}
}
}else {
//情況三
for(let i = 0; i < this.length; i++) {
this.setStyle(this[i], args[0], args[1]);
}
}
}
增加cssNumber方法來(lái)確定不用加px的屬性名
//css方法用
$.cssNumber = {
animationIterationCount: true,
columnCount: true,
fillOpacity: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
gridArea: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnStart: true,
gridRow: true,
gridRowEnd: true,
gridRowStart: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true
}
最后獻(xiàn)上完整代碼,如果大哥們覺(jué)的不錯(cuò),給個(gè)贊唄
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> .box1 {
width: 100px;
height: 100px;
background: red;
}
.box2 {
width: 100px;
height: 100px;
background: blue;
transform-origin: 0 100% 0;
transition: 0.3s;
}
.box2:hover {
transform: scaleX(2);
width: 200px;
height: 100px;
} </style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<button>點(diǎn)擊</button>
</body>
<script> class jquery {
constructor(arg, root) {
if(typeof root === "undefined") {
this.prevObject = [document];
}else {
this.prevObject = root;
}
//情況一
if(typeof arg === 'string') {
this.addEles(document.querySelectorAll(arg));
}else if(typeof arg === 'function') {
//情況二
document.addEventListener("DOMContentLoaded", arg);
}else {
//情況三
if(typeof arg.length === 'undefined') {
this[0] = arg;
this.length = 1;
}else {
this.addEles(arg);
}
}
}
//增加方法
addEles(eles){
for (let i = 0; i < eles.length; i++) {
this[i] = eles[i];
}
this.length = eles.length;
}
//鏈?zhǔn)讲僮?
//劃重點(diǎn),在on和click中添加return即可實(shí)現(xiàn)鏈?zhǔn)?
// click方法
click(fn) {
for(let i = 0; i < this.length; i++) {
this[i].addEventListener("click", fn);
}
return this;
// console.log(this);
}
// on方法
on(eventName, fn) {
let eventArray = eventName.split(" ");
//考慮多個(gè)節(jié)點(diǎn)
for(let i = 0; i < this.length; i++) {
//考慮多個(gè)事件
for(let j = 0; j < eventArray.length; j++) {
this[i].addEventListener(eventArray[j], fn);
}
}
return this;
}
//eq方法
eq(index) {
return new jquery(this[index], this);
}
//end方法
end() {
return this.prevObject;
}
//css方法
css(...args) {
if(args.length === 1) {
//情況一:獲取樣式
if(typeof args[0] === 'string') {
return this.getStyle(this[0], args[0]);
}else {
//情況三:設(shè)置多個(gè)樣式
for(let i = 0; i < this.length; i++) {
for(let j in args[0]) {
this.setStyle(this[i], j, args[0][j]);
}
}
}
}else {
//情況三
for(let i = 0; i < this.length; i++) {
this.setStyle(this[i], args[0], args[1]);
}
}
}
getStyle(ele, styleName) {
return window.getComputedStyle(ele, null)[styleName];
}
setStyle(ele, styleName, styleValue) {
if(typeof styleValue === "number" && !(styleName in $.cssNumber)) {
styleValue = styleValue + "px";
}
ele.style[styleName] = styleValue;
}
}
function $(arg) {
return new jquery(arg);
}
//css方法用
$.cssNumber = {
animationIterationCount: true,
columnCount: true,
fillOpacity: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
gridArea: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnStart: true,
gridRow: true,
gridRowEnd: true,
gridRowStart: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true
}
// //實(shí)現(xiàn)情況一:$(".box1")
// $("div").click(() => {
// console.log("123")
// });
// //實(shí)現(xiàn)情況二:參數(shù)為函數(shù)
// $(function() {
// console.log('情況2');
// })
// // 情況三
// $(document.querySelectorAll("div")).click(()=>{
// console.log("123");
// })
// $(document.querySelector("div")).click(()=>{
// console.log("456");
// })
// // on方法
// $("div").on("mouseover mousedown",function(){
// console.log("on方法");
// })
//鏈?zhǔn)讲僮?
// $("div").click(() => {
// console.log("click方法")
// }).on("mouseover", function() {
// console.log('鏈?zhǔn)給n方法');
// })
// $("div").on("mouseover", function() {
// console.log('鏈?zhǔn)給n方法');
// }).click(() => {
// console.log("click方法")
// })
// //eq方法
// $("div").eq(0).click(() => {
// console.log("eq方法")
// })
//endf方法
// let res = $("div").eq(0).eq(0).eq(0).end();
// console.log(res);
//css方法
// 情況一 :獲取樣式 (只去獲取第一個(gè)元素)
// let res = $("div").css("background");
// console.log(res);
// 情況二 (設(shè)置樣式)
// $("div").css("background","yellow");
// // 情況三 (設(shè)置多個(gè)樣式)
// $("div").css({background:"black",width:200,opacity:0.3}); </script>
</html>
總結(jié)
到此這篇關(guān)于js實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法與鏈?zhǔn)讲僮鞯奈恼戮徒榻B到這了,更多相關(guān)js封裝jQuery內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
-
javascript encodeURI和encodeURIComponent的比較
在進(jìn)行SaaS前端開(kāi)發(fā)的時(shí)候,大家經(jīng)常會(huì)用到兩個(gè)JavaScriptNative函數(shù):encodeURI 和 encodeURIComponent。這篇文章詳細(xì)解釋這兩個(gè)函數(shù)的用途并比較它們的不同之處 2010-04-04
-
JavaScript詞法作用域與調(diào)用對(duì)象深入理解
關(guān)于 Javascript 的函數(shù)作用域、調(diào)用對(duì)象和閉包之間的關(guān)系很微妙,關(guān)于它們的文章已經(jīng)有很多,本文做了一些總結(jié),需要的朋友可以參考下 2012-11-11
-
詳解JavaScript如何有效取消HTTP請(qǐng)求
在Web開(kāi)發(fā)中,取消HTTP請(qǐng)求是一項(xiàng)關(guān)鍵任務(wù),所以本文為大家介紹了如何使用XMLHttpRequest、Fetch和Axios這三種常用的HTTP請(qǐng)求方式來(lái)實(shí)現(xiàn)取消請(qǐng)求的功能,需要的可以參考下 2023-09-09
-
BootStrap 獲得輪播中的索引和當(dāng)前活動(dòng)的焦點(diǎn)對(duì)象
這篇文章主要介紹了BootStrap 獲得輪播中的索引和當(dāng)前活動(dòng)的焦點(diǎn)對(duì)象,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下 2017-05-05
-
原生js實(shí)現(xiàn)水平方向無(wú)縫滾動(dòng)
這篇文章主要為大家詳細(xì)介紹了原生js實(shí)現(xiàn)水平方向無(wú)縫滾動(dòng)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下 2017-01-01
-
javascript中利用數(shù)組實(shí)現(xiàn)的循環(huán)隊(duì)列代碼
javascript中利用數(shù)組實(shí)現(xiàn)的循環(huán)隊(duì)列代碼,需要的朋友可以參考下。 2010-01-01
最新評(píng)論
我用這篇文章來(lái)理一理如何用js去實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法。
本文js實(shí)現(xiàn)了下面jquery的幾種方法,我將它分為8個(gè)小目標(biāo)
- 實(shí)現(xiàn)$(".box1").click( )方法
- 實(shí)現(xiàn)$("div").click( )方法
- 考慮$( )中參數(shù)的三種情況
- 實(shí)現(xiàn)jq中的on方法
- 實(shí)現(xiàn)鏈?zhǔn)讲僮?/li>
- 實(shí)現(xiàn)jq中的eq方法
- 實(shí)現(xiàn)jq中的end方法
- 實(shí)現(xiàn)jq中的css方法
有不正確的地方還望大家在評(píng)論區(qū)指出來(lái),謝謝啦。
1. 實(shí)現(xiàn)$(".box1").click( )方法
首先,我們定第一個(gè)小目標(biāo),就是如何一步一步去實(shí)現(xiàn)下方j(luò)Query代碼的功能。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> //同一個(gè)文件下操作的話,后面記得刪除下面引入的cdn <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <style> .box1 { width: 100px; height: 100px; background: red; } </style> </head> <body> <div class="box1"></div> </body> <script> $(".box1").click(()=>{ console.log(456); }) </script> </html> 復(fù)制代碼
$(".box1").click(()=>{ console.log(456); })
好了,言歸正傳,我們來(lái)分析上面jQuery的代碼。
- $(".box1") 就是實(shí)現(xiàn)了選擇器的功能。
- $(".box1").click 就是選擇器 + 調(diào)用click方法
- 最后在click里面?zhèn)魅牒瘮?shù)。
第一個(gè)小目標(biāo)就是自己封裝js來(lái)實(shí)現(xiàn)上面代碼的功能。我們分三步走戰(zhàn)略來(lái)實(shí)現(xiàn)。
- js實(shí)現(xiàn) $(".box1")
- 實(shí)現(xiàn) $(".box1").click()
- 實(shí)現(xiàn) $(".box1").click( ( ) => { console.log("123") } )
第一步就是先用js實(shí)現(xiàn) $(".box1"), 對(duì)吧
// 實(shí)現(xiàn)$(".box1") class jquery { constructor(arg) { console.log(document.querySelector(arg)); } } function $(arg) { return new jquery(arg); } // 實(shí)現(xiàn)$(".box1") let res = $(".box1"); console.log(res);
這樣是不是就通過(guò)構(gòu)建()方法并返回jquery實(shí)例,實(shí)現(xiàn)了(".box1")呢。
那好,接下來(lái)我們進(jìn)行第二步就是實(shí)現(xiàn) $(".box1").click()。相信大家也看出來(lái)了,就是在jquery類中多了一個(gè)click方法。
// 實(shí)現(xiàn)$(".box1").click() class jquery { constructor(arg) { console.log(document.querySelector(arg)); } click() { console.log("執(zhí)行了click方法"); } } function $(arg) { return new jquery(arg); } // 實(shí)現(xiàn)$(".box1").click() let res = $(".box1").click(); console.log(res);
接下來(lái),我們進(jìn)行第三步就是實(shí)現(xiàn) $(".box1").click( ( ) => { console.log("123") } )。
// 實(shí)現(xiàn)$(".box1").click(() => {console.log("123")}) class jquery { constructor(arg) { this.element = document.querySelector(arg); // console.log(element); } click(fn) { this.element.addEventListener("click", fn); } } function $(arg) { return new jquery(arg); } //實(shí)現(xiàn)$(".box1").click(() => {console.log("123")}) $(".box1").click(() => { console.log("123") });
到此為止,我們實(shí)現(xiàn)了第一個(gè)小目標(biāo),大家是不是覺(jué)得簡(jiǎn)單呢,ok,接下來(lái)我們繼續(xù)第二個(gè)小目標(biāo)。
2. 實(shí)現(xiàn)$("div").click( )方法
第二個(gè)小目標(biāo)也不難,就是考慮有多個(gè)div元素需要綁定click事件,我們用selectSelectorAll來(lái)獲取元素的話,如何處理,其實(shí)也挺簡(jiǎn)單,就是在click方法中多出一個(gè)循環(huán),去獲取NodeList中的值。我直接上代碼了,大家試一試就知道啦。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1 { width: 100px; height: 100px; background: red; } .box2 { width: 100px; height: 100px; background: blue; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> <script> // 實(shí)現(xiàn)$(".box1").click(() => {console.log("123")}) class jquery { constructor(arg) { //下面element存的是NodeList對(duì)象,它是一個(gè)類數(shù)組有l(wèi)ength屬性 this.element = document.querySelectorAll(arg); } click(fn) { for(let i = 0; i < this.element.length; i++) { this.element[i].addEventListener("click", fn); } } } function $(arg) { return new jquery(arg); } //實(shí)現(xiàn)$(".box1").click(() => {console.log("123")}) $("div").click(() => { console.log("123") }); </script> </html>
好了,完成兩個(gè)小目標(biāo)了,相信你已經(jīng)有成就感了。
3. 考慮$( )中參數(shù)的三種情況
接下來(lái)第三個(gè)小目標(biāo) 我們來(lái)考慮一下$( )中參數(shù)不同的情況,我先將三種情況列出來(lái)。(可能還有其他情況,這里就不說(shuō)了)
1.情況一:就是$( )參數(shù)為字符串
$(".box1")
2.情況二:就是$( )參數(shù)為函數(shù)的情況。
//參數(shù)為函數(shù) $(function() { console.log("123"); })
3.情況三:就是$( )參數(shù)為NodeList對(duì)象或selectSelect獲得的節(jié)點(diǎn)
// 情況三 $(document.querySelectorAll("div")).click(()=>{ console.log("123"); }) $(document.querySelector("div")).click(()=>{ console.log("456"); })
接下來(lái)第三個(gè)小目標(biāo)是手寫函數(shù)來(lái)實(shí)現(xiàn)三種情況。 首先我們?cè)黾觓ddEles方法,修改上面的click方法
addEles(eles){ for (let i = 0; i < eles.length; i++) { this[i] = eles[i]; } this.length = eles.length; } // 實(shí)現(xiàn)$(".box1").click(() => {console.log("123")}) click(fn) { for(let i = 0; i < this.length; i++) { this[i].addEventListener("click", fn); } }
接下來(lái)實(shí)現(xiàn)三種不同參數(shù)的處理方法
constructor(arg) { //情況一 if(typeof arg === 'string') { this.addEles(document.querySelectorAll(arg)); }else if(typeof arg === 'function') { //情況二 document.addEventListener("DOMContentLoaded", arg); }else { //情況三 if(typeof arg.length === 'undefined') { this[0] = arg; this.length = 1; }else { this.addEles(arg); } } }
4. 實(shí)現(xiàn)jq中的on方法
接下來(lái)實(shí)現(xiàn)第四個(gè)小目標(biāo) 實(shí)現(xiàn)jq的on方法
// on方法 on(eventName, fn) { let eventArray = eventName.split(" "); //考慮多個(gè)節(jié)點(diǎn) for(let i = 0; i < this.length; i++) { //考慮多個(gè)事件 for(let j = 0; j < eventArray.length; j++) { this[i].addEventListener(eventArray[j], fn); } } }
再測(cè)試下ok不
// on方法 $("div").on("mouseover mousedown",function(){ console.log("on方法"); })
5. 實(shí)現(xiàn)鏈?zhǔn)讲僮?br />
接下來(lái)實(shí)現(xiàn)第五個(gè)小目標(biāo) 實(shí)現(xiàn)jq的鏈?zhǔn)讲僮?/p>
劃重點(diǎn),在on和click中添加return this即可實(shí)現(xiàn)鏈?zhǔn)?/p>
//鏈?zhǔn)讲僮? //劃重點(diǎn),在on和click中添加return this即可實(shí)現(xiàn)鏈?zhǔn)? // click方法 click(fn) { for(let i = 0; i < this.length; i++) { this[i].addEventListener("click", fn); } return this; // console.log(this); } // on方法 on(eventName, fn) { let eventArray = eventName.split(" "); //考慮多個(gè)節(jié)點(diǎn) for(let i = 0; i < this.length; i++) { //考慮多個(gè)事件 for(let j = 0; j < eventArray.length; j++) { this[i].addEventListener(eventArray[j], fn); } } return this; }
6. 實(shí)現(xiàn)jq中的eq方法
接下來(lái)實(shí)現(xiàn)第六個(gè)小目標(biāo) 實(shí)現(xiàn)jq中的eq方法
//eq方法 eq(index) { return new jquery(this[index]); }
這里通過(guò)new一個(gè)jquery實(shí)現(xiàn) new的過(guò)程大家應(yīng)該清楚吧,我們溫習(xí)一下:
- 執(zhí)行函數(shù)
- 自動(dòng)創(chuàng)建一個(gè)空對(duì)象
- 將空對(duì)象的原型指向構(gòu)造函數(shù)的prototype屬性
- 將空對(duì)象和函數(shù)內(nèi)部this綁定
- 如果renturn后跟著對(duì)象,返回這個(gè)對(duì)象。沒(méi)跟的話就自動(dòng)返回this對(duì)象
7. 實(shí)現(xiàn)jq中的end方法
實(shí)現(xiàn)第七個(gè)小目標(biāo) 實(shí)現(xiàn)jq中的end方法。要實(shí)現(xiàn)這個(gè)功能,除了新增end( )方法,我們還得在構(gòu)造函數(shù)上實(shí)現(xiàn),constructor新增參數(shù)root,新增屬性prevObject,并在eq方法這種新增參數(shù)this。
constructor(arg, root) { if(typeof root === "undefined") { this.prevObject = [document]; }else { this.prevObject = root; } //eq方法 eq(index) { return new jquery(this[index], this); } //end方法 end() { return this.prevObject; }
8. 實(shí)現(xiàn)jq中的css方法
在jq中css可以獲取樣式,設(shè)置一個(gè)樣式或多個(gè)樣式
// 情況一 :獲取樣式 (只去獲取第一個(gè)元素) let res = $("div").css("background"); console.log(res); // 情況二 (設(shè)置樣式) $("div").css("background","yellow"); // // 情況三 (設(shè)置多個(gè)樣式) $("div").css({background:"black",width:200,opacity:0.3});
接下來(lái)實(shí)現(xiàn)css方法
//css方法 css(...args) { if(args.length === 1) { //情況一:獲取樣式 if(typeof args[0] === 'string') { return this.getStyle(this[0], args[0]); }else { //情況三:設(shè)置多個(gè)樣式 for(let i = 0; i < this.length; i++) { for(let j in args[0]) { this.setStyle(this[i], j, args[0][j]); } } } }else { //情況三 for(let i = 0; i < this.length; i++) { this.setStyle(this[i], args[0], args[1]); } } } //css方法 css(...args) { if(args.length === 1) { //情況一:獲取樣式 if(typeof args[0] === 'string') { return this.getStyle(this[0], args[0]); }else { //情況三:設(shè)置多個(gè)樣式 for(let i = 0; i < this.length; i++) { for(let j in args[0]) { this.setStyle(this[i], j, args[0][j]); } } } }else { //情況三 for(let i = 0; i < this.length; i++) { this.setStyle(this[i], args[0], args[1]); } } }
增加cssNumber方法來(lái)確定不用加px的屬性名
//css方法用 $.cssNumber = { animationIterationCount: true, columnCount: true, fillOpacity: true, flexGrow: true, flexShrink: true, fontWeight: true, gridArea: true, gridColumn: true, gridColumnEnd: true, gridColumnStart: true, gridRow: true, gridRowEnd: true, gridRowStart: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true }
最后獻(xiàn)上完整代碼,如果大哥們覺(jué)的不錯(cuò),給個(gè)贊唄
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1 { width: 100px; height: 100px; background: red; } .box2 { width: 100px; height: 100px; background: blue; transform-origin: 0 100% 0; transition: 0.3s; } .box2:hover { transform: scaleX(2); width: 200px; height: 100px; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> <button>點(diǎn)擊</button> </body> <script> class jquery { constructor(arg, root) { if(typeof root === "undefined") { this.prevObject = [document]; }else { this.prevObject = root; } //情況一 if(typeof arg === 'string') { this.addEles(document.querySelectorAll(arg)); }else if(typeof arg === 'function') { //情況二 document.addEventListener("DOMContentLoaded", arg); }else { //情況三 if(typeof arg.length === 'undefined') { this[0] = arg; this.length = 1; }else { this.addEles(arg); } } } //增加方法 addEles(eles){ for (let i = 0; i < eles.length; i++) { this[i] = eles[i]; } this.length = eles.length; } //鏈?zhǔn)讲僮? //劃重點(diǎn),在on和click中添加return即可實(shí)現(xiàn)鏈?zhǔn)? // click方法 click(fn) { for(let i = 0; i < this.length; i++) { this[i].addEventListener("click", fn); } return this; // console.log(this); } // on方法 on(eventName, fn) { let eventArray = eventName.split(" "); //考慮多個(gè)節(jié)點(diǎn) for(let i = 0; i < this.length; i++) { //考慮多個(gè)事件 for(let j = 0; j < eventArray.length; j++) { this[i].addEventListener(eventArray[j], fn); } } return this; } //eq方法 eq(index) { return new jquery(this[index], this); } //end方法 end() { return this.prevObject; } //css方法 css(...args) { if(args.length === 1) { //情況一:獲取樣式 if(typeof args[0] === 'string') { return this.getStyle(this[0], args[0]); }else { //情況三:設(shè)置多個(gè)樣式 for(let i = 0; i < this.length; i++) { for(let j in args[0]) { this.setStyle(this[i], j, args[0][j]); } } } }else { //情況三 for(let i = 0; i < this.length; i++) { this.setStyle(this[i], args[0], args[1]); } } } getStyle(ele, styleName) { return window.getComputedStyle(ele, null)[styleName]; } setStyle(ele, styleName, styleValue) { if(typeof styleValue === "number" && !(styleName in $.cssNumber)) { styleValue = styleValue + "px"; } ele.style[styleName] = styleValue; } } function $(arg) { return new jquery(arg); } //css方法用 $.cssNumber = { animationIterationCount: true, columnCount: true, fillOpacity: true, flexGrow: true, flexShrink: true, fontWeight: true, gridArea: true, gridColumn: true, gridColumnEnd: true, gridColumnStart: true, gridRow: true, gridRowEnd: true, gridRowStart: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true } // //實(shí)現(xiàn)情況一:$(".box1") // $("div").click(() => { // console.log("123") // }); // //實(shí)現(xiàn)情況二:參數(shù)為函數(shù) // $(function() { // console.log('情況2'); // }) // // 情況三 // $(document.querySelectorAll("div")).click(()=>{ // console.log("123"); // }) // $(document.querySelector("div")).click(()=>{ // console.log("456"); // }) // // on方法 // $("div").on("mouseover mousedown",function(){ // console.log("on方法"); // }) //鏈?zhǔn)讲僮? // $("div").click(() => { // console.log("click方法") // }).on("mouseover", function() { // console.log('鏈?zhǔn)給n方法'); // }) // $("div").on("mouseover", function() { // console.log('鏈?zhǔn)給n方法'); // }).click(() => { // console.log("click方法") // }) // //eq方法 // $("div").eq(0).click(() => { // console.log("eq方法") // }) //endf方法 // let res = $("div").eq(0).eq(0).eq(0).end(); // console.log(res); //css方法 // 情況一 :獲取樣式 (只去獲取第一個(gè)元素) // let res = $("div").css("background"); // console.log(res); // 情況二 (設(shè)置樣式) // $("div").css("background","yellow"); // // 情況三 (設(shè)置多個(gè)樣式) // $("div").css({background:"black",width:200,opacity:0.3}); </script> </html>
總結(jié)
到此這篇關(guān)于js實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法與鏈?zhǔn)讲僮鞯奈恼戮徒榻B到這了,更多相關(guān)js封裝jQuery內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript encodeURI和encodeURIComponent的比較
在進(jìn)行SaaS前端開(kāi)發(fā)的時(shí)候,大家經(jīng)常會(huì)用到兩個(gè)JavaScriptNative函數(shù):encodeURI 和 encodeURIComponent。這篇文章詳細(xì)解釋這兩個(gè)函數(shù)的用途并比較它們的不同之處2010-04-04JavaScript詞法作用域與調(diào)用對(duì)象深入理解
關(guān)于 Javascript 的函數(shù)作用域、調(diào)用對(duì)象和閉包之間的關(guān)系很微妙,關(guān)于它們的文章已經(jīng)有很多,本文做了一些總結(jié),需要的朋友可以參考下2012-11-11詳解JavaScript如何有效取消HTTP請(qǐng)求
在Web開(kāi)發(fā)中,取消HTTP請(qǐng)求是一項(xiàng)關(guān)鍵任務(wù),所以本文為大家介紹了如何使用XMLHttpRequest、Fetch和Axios這三種常用的HTTP請(qǐng)求方式來(lái)實(shí)現(xiàn)取消請(qǐng)求的功能,需要的可以參考下2023-09-09BootStrap 獲得輪播中的索引和當(dāng)前活動(dòng)的焦點(diǎn)對(duì)象
這篇文章主要介紹了BootStrap 獲得輪播中的索引和當(dāng)前活動(dòng)的焦點(diǎn)對(duì)象,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2017-05-05原生js實(shí)現(xiàn)水平方向無(wú)縫滾動(dòng)
這篇文章主要為大家詳細(xì)介紹了原生js實(shí)現(xiàn)水平方向無(wú)縫滾動(dòng)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01javascript中利用數(shù)組實(shí)現(xiàn)的循環(huán)隊(duì)列代碼
javascript中利用數(shù)組實(shí)現(xiàn)的循環(huán)隊(duì)列代碼,需要的朋友可以參考下。2010-01-01