简单实现jQuery的一个API

先抛JS代码:
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.$ = jquery;
var $div = $('div')
$div.addClass('red') // 可将所有 div 的 class 添加一个 red
$div.setText('hi') // 可将所有 div 的 textContent 变为 hi
代码实现两个功能,1.给标签添加一个class属性,2.更改标签里面的文本;
代码分析:
     1.在window上生成一个jQuery的命名空间
   2. 根据判断传入的值的类型用不同的方法把获取到的元素放入伪数组nodes;
   3.给nodes添加addClass属性,这个属性的功能是用for循环把获取到的所有元素上添加统一的class属性;//  或者传入数组用classes.forEach(function(){})来指定添加class;
   4.setText属性,传入一个字符串等,让获取元素的textContent改成传入的文本,同样用for循环来实现;//  加不同文本方法同上
   5.在window上生成一个$来代表jQuery,方便操作和使用,这样我们就做出了“jQuery的两个功能”。
 

猜你喜欢

转载自www.cnblogs.com/triplewoodsaid/p/9888026.html