jQuery就是一個(gè)函數(shù),接收一個(gè)參數(shù)箫攀,然后返回一個(gè)方法對(duì)象來操作DOM牢贸。
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) {
if (text === undefined) {
let texts = [];
for (let i = 0; i < nodes.length; i++) {
texts.push(nodes[i].textContent)
}
return texts;
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text;
}
}
}
return nodes;
}
window.$ = jQuery;
var $div = $('div');
$div.addClass('red');
$div.setText('hi')
上述代碼將一個(gè)函數(shù)賦值給window.jquey,然后更改名字為$,
通過$('xxx').方法就可以調(diào)用window.jquey里面的方法土辩,不用擔(dān)心沖突等問題,使用也更方便一些