写在最前面:对 jQuery 的初步认识,以及自己对 jQuery 的摸索.
首先实现我需要的函数
function getSiblings(node){}
和
function addClass(node, classes){}
如下:
function getSiblings(node){
var allNodes = node.parentNode.children;
var array = {length: 0};
for(let i= 0; i < allNodes.length; i++){
if(allNodes[i] !== node){
array[array.length] = allNodes[i]
length++;
}
}
return array;
}
function addClass(node, classes){
classes.forEach( (value) => node.classList.add(value) )
}
尝试再给加上命名空间:
var dom = {
getSiblings: function getSiblings(node){...}
addClass: function addClass(node, classes){...}
}
再考虑下能不能做的更直观一些:
我们可以试着将其放到 Node 接口上 (Node.prototype)
Node.prototype.getSiblings = function (){...}
Node.prototype.addClass = function(classes){...}
例如:item.getSiblings();
这样一来我们可以直接用元素来直接使用.但是也会带来一些问题:例如全局污染,出了 Bug 不容易定位问题以及会与其他引入的库造成冲突.所以一般来说,我们不应该直接在原型上添加方法.
Another way
使用我们自己的接口来封装例如'jQuery'
function jQuery(node){
return {
element: node,
getSiblings: function(){},
addClass: function(classes){}
}
}
这样一来,我们可以轻松的使用方法,并且不再担心对后续的影响,如果再来一个 alisa 就更完美了!window.$ = jQuery:
var x = document.getElementById('x');
var $myNode = $(x)
$myNode.getSiblings();
$myNode.addClass('color');
完整代码 (添加了 text 方法)
window.jQuery = function(nodeOrSelector){
var nodes = {};
if(nodeOrSelector === 'string'){
let things = document.querySelectorAll(nodeOrSelector);
for(let i = 0; i< things.length; i++){
nodes[i] = things[i];
}
nodes.length = things.length;
}else if(nodeOrSelector instanceof Node){
nodes = {0: nodeOrSelector, length: 1}
}
nodes.getSiblings = function(){
let allNodes = nodes.parentNode.children;
let array = {length: 0}
for(let i = 0; i < allNodes.length; i++){
if(allNodes !== nodes){
array[array.length] = allNodes[i];
length++;
}
}
return array;
}
nodes.addClass = function(classes){
classes.forEach(value => {
for(let i = 0; i < nodes.length; i++)
nodes[i].classList.add(value);
}
})
}
nodes.getText = function(){
let text = [];
for(let i = 0; i < nodes.length; i++){
text.push(nodes[i].textContent);
}
return text;
}
nodes.setText = function(text){
for(let i = 0; i < nodes.length; i++){
nodes[i].textContent = text;
}
}
return nodes;
}
到这里算是模仿了 jQuery 是如何让人们方便的使用它.
来源: https://juejin.im/post/5a6585c06fb9a01cbe656ff3