jQuery入门
首先直接完成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 = https://www.it610.com/article/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 = https://www.it610.com/article/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'])
【jQuery入门】使用包装对象,减少冲突
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'])
推荐阅读
- 【生信技能树】R语言练习题|【生信技能树】R语言练习题 - 中级
- 事件代理
- 最好的生活,首先是好好活着
- 阿修罗|仨头镶钻,也哄不住5岁小孩
- jQuery插件
- typeScript入门基础介绍
- 六级没过,考研英语70分难不难
- 7、前端--jQuery简介、基本选择器、基本筛选器、属性选择器、表单选择器、筛选器方法、节点操作、绑定事件
- Android|Android sqlite3数据库入门系列
- Android下的IO库-Okio源码解析(一)|Android下的IO库-Okio源码解析(一) 入门