摘要:本篇jQuery教程探讨了如何自己做一个jQuery,希望阅读本篇文章以后大家有所收获,帮助大家对jQuery的理解更加深入。
什么是jQuery?
jQuery本质只是一个中间层,提供一套统一易用的DOM操作接口。
那么,今天我们就来自己实现一个简易版的jQuery
首先我们来实现选择器
window.jQuery = function(nodeOrSelector){
let nodes = {} //统一使用对象
//首先我们需要判断用户是想获取多个元素节点还是一个
if(typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)
//遍历临时对象temp,将他的值放入nodes内,这样我们就能得到一个纯净的对象,而不是querySelectorAll返回的NodeList
for(let i=0;i<temp.length;i++){
nodes[i] = temp[i]
}
nodes.length = temp.length
//如果用户传入的是一个节点,那么就只针对这个节点进行后续操作
} else if(nodeOrSelector instanceof Node){
nodes = {
0: nodeOrSelector,
length: 1
}
}
return nodes //返回nodes
}
接下来我们为nodes添加addClass方法:
//classes是用户想要添加的class名
nodes.addClass = function(classes){
//遍历nodes,为nodes内每一个元素节点添加class
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(classes)
}
}
最后我们为nodes添加setText方法:
//text是用户想要添加的文本
nodes.setText = function(text){
//遍历nodes,为nodes内每一个元素节点的textContent添加text
for(let i=0;i<nodes.length;i++){
nodes[i].textContent = text
}
}
最后我们再创建一个window对象
window.$ = window.jQuery
下面是完整代码
window.jQuery = function(nodeOrSelector){
let nodes = {}
if(typeof nodeOrSelector === 'string'){
let temp = document.querySelectorAll(nodeOrSelector)
for(let i=0;i<temp.length;i++){
nodes[i] = temp[i]
}
nodes.length = temp.length
} else if(nodeOrSelector instanceof Node){
nodes = {
0: nodeOrSelector,
length: 1
}
}
nodes.addClass = function(classes){
for(let i=0;i<nodes.length;i++){
nodes[i].classList.add(classes)
}
}
nodes.setText = function(text){
for(let i=0;i<nodes.length;i++){
nodes[i].textContent = text
}
}
return nodes
}
window.$ = window.jQueryvar $div = $('div') //获取所有div元素
$div.addClass('red')
$div.setText('hi')
ok,这样我们就初步实现了自己的简易版jQuery(以上使用到了闭包)。
本文由职坐标整理发布,更多相关内容,请关注职坐标WEB前端jQuery频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号