blog
blog copied to clipboard
写一个jQuery
用法我就不多说了,跟jquery差不多,而且目前也就~我一个人用~我不用jQuery。
class Query {
constructor(selector) {
this.elements = document.querySelectorAll(selector);
this.author = 'pengliheng';
this.version = '0.0.1';
}
// 写方法
css(key, val) {
this.elements.forEach((dom) => { dom.style[key] = val; });
return this;
}
// 选择第i个元素
eq(i) {
this.elements = [this.elements[i]];
return this;
}
// find,查找///
find(selector) {
let newNode = [];
this.elements.forEach((dom) => {
newNode = [
...newNode,
...dom.querySelectorAll(selector),
];
});
this.elements = newNode;
return this;
}
attr(attr, val) {
this.elements.forEach((dom) => {
if (attr.match(/data-/)) {
dom.dataset[attr.match(/(?<=-)\w*/g)] = val;
} else {
dom[attr] = val;
}
});
return this;
}
click(func) {
this.elements.forEach(dom=>{
dom.addEventListener('click',e=>func(e))
})
return this
}
each(func){
this.elements.forEach(dom=>{
func(dom)
})
return this;
}
}
const $ = selector => new Query(selector);
// 用于写属性
$.ajax = ({
type, url, dataType, success, error, data,
}) => {
fetch(url, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: type,
body: JSON.stringify(data),
// credentials: 'include'
})
.then(res => res[dataType]())
.then(suc => success(suc))
.catch(err => error(err));
};
window.$ = $;
usage
$('li').eq(9).css('background','red').css('font-size',"25px").css('font-size',"25px")
$.ajax({
type: "POST",
url: `https://chat.pipk.top/graphql`,
dataType: "json",
data:{
query: `{
search(query: "${name||'pengliheng'}", type: USER, first: 1) {
edges {
node {
... on User {
login
}
}
}
}
}`,
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
$('li').find('#checkbox').attr('data-id','rgfhgfhgfo');
$('li').find('#checkbox').attr('id','privaty');
$('svg').css('background', 'red').click((e) => {
$('li').each((e) => {
console.log(e);
});
});