首先直接完成api 用参数传入调用对象
let item3 = document.getElementById('item3');
function getSiblings(node) {
let allChildren = node.parentNode.children;
let array = { length: 0 }
for (let i = 0; i < allChildren.length; i++) {
if (allChildren[i] !== node) {
array[array.length] = allChildren[i];
array.length += 1;
}
}
return array;
}
console.log(getSiblings(item3));
function addClasses(node,classes){
for(let key in classes){
let value = classes[key];
if(value){
node.classList.add(key);
}else{
node.classList.remove(key);
}
}
}
addClasses(item3,{'a':true,'b':false,'c':true});
优化函数逻辑
function addClasses(node, classes) {
for (let key in classes) {
let value = classes[key];
let methodName = value ? 'add' : 'remove';
node.classList[methodName](key);
}
}
addClasses(item3, { 'a': true, 'b': false, 'c': true });
使用命名空间,减少全局对象数量
window.xxdom = {};
xxdom.getSiblings = function (node) {
let allChildren = node.parentNode.children;
let array = { length: 0 }
for (let i = 0; i < allChildren.length; i++) {
if (allChildren[i] !== node) {
array[array.length] = allChildren[i];
array.length += 1;
}
}
return array;
}
xxdom.addClasses = function addClasses(node, classes) {
classes.forEach((value) => item3.classList.add(value));
}
直接改写prototype对象,方便使用时调用
Node.prototype.getSiblings = function () {
let allChildren = this.parentNode.children;
let array = { length: 0 }
for (let i = 0; i < allChildren.length; i++) {
if (allChildren[i] !== this ){
array[array.length] = allChildren[i];
array.length += 1;
}
}
return array;
}
Node.prototype.addClasses = function addClasses(classes) {
classes.forEach((value) => this.classList.add(value));
}
console.log(item3.getSiblings());
item3.addClasses(['a','d'])
使用包装对象,减少冲突
window.jQuery = function (nodeOrSelector) {
let nodes = {};
if (typeof nodeOrSelector === 'string') {
let tmp = document.querySelectorAll(nodeOrSelector);
for (let i = 0; i < tmp.length; i++) {
nodes[i] = tmp[i];
nodes.length = tmp.length;
}
} else if (nodeOrSelector instanceof Node) {
nodes = {
0: querySelectorAll,
length: 1
};
}
nodes.addClass = function (classes) {
classes.forEach((value) => {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(value);
}
});
}
nodes.setText = function(text){
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text;
}
}
return nodes;
}
let node2 = jQuery('ul > li');
node2.addClass(['a', 'e'])
网友评论