利用原生js获取节点需要重复相同获取节点的代码,使得代码量变大,封装之后获取节点就非常的方便,该方法不仅能获取节点,还能生成一些常用的方法,方便后期调用,减少代码量,优化开发效率。
(function (){
// 初始化
function init(selector){
return new jqruy(selector)
}
// 生成节点
function jqruy(selector){
this.node='';//节点
if (/^#/.test(selector)){
// console.log(selector.substring(1))
this.node=document.getElementById(selector.substring(1))
}else if (/^\./.test(selector)){
this.node=document.getElementsByClassName(selector.substring(1))
}else if(/\d/.test(selector)){
this.node=document.getElementsByTagName(selector)
}
}
// 添加方法
jqruy.prototype.html=function (str){
this.node.innerHTML=str
}
jqruy.prototype.css=function (attr,value){
this.node.style.attr=value
}
// 为init函数添加方法
init.ajax=function (str){
// this.node.innerHTML=str
console.log('ajax')
}
// 扩展方法
init.extend=function (obj){
console.log(obj)
for(let key in obj){
init[key]=obj[key]
}
}
window.$= init
})()
$('#on').html()//调用html方法
$('#on').css()//调用css方法
$.ajax()//调用方法
// 扩展方法
$.extend({
each:function (){
console.log("each")
},
newFn:function (){
console.log("newFn")
}
})
$.each();
$.newFn();