大家好,又见面了,我是你们的朋友全栈君。
class jQuery {
constructor(selector) {
let splitSelector = selector.match(/([$#])(.*)/);
if (splitSelector) {
if (Object.is(splitSelector[1], '$')) {
this.dom = document.querySelectorAll(splitSelector[2]);
} else if (Object.is(splitSelector[1], '#')) {
this.dom = document.getElementById(splitSelector[2]);
} else {
this.dom = document.querySelectorAll(selector);
}
} else {
this.dom = document.querySelectorAll(selector);
}
}
_isObject(obj) {
const _toString = Object.prototype.toString;
return Object.is(_toString.call(obj), '[object Object]');
}
addClass(className) {
if (className) {
if (this.dom.className) {
let classList = this.dom.className.split(' ');
let classNameList = className.split(' ');
let concatClassList = classList.concat(classNameList);
concatClassList = [...new Set(concatClassList)];
this.dom.className = concatClassList.join(' ');
} else {
this.dom.className = `${className}`;
}
} else {
throw new Error('必须传递参数');
}
return this;
}
removeClass(className) {
if (className) {
let classList = this.dom.className.split(' ');
classList.splice(classList.findIndex(item => Object.is(item, className)), 1);
this.dom.className = classList.join(' ');
} else {
throw new Error('必须传递参数');
}
return this;
}
html(data) {
this.dom.innerHTML = data;
return this;
}
css(params) {
if (params) {
if (this._isObject(params)) {
for (let key in params) {
this.dom.style[key] += params[key];
}
} else {
if (arguments.length != 2) {
throw new Error();
} else {
this.dom.style[arguments[0]] = arguments[1];
}
}
} else {
throw new Error('必须传递参数');
}
return this;
}
}
window.$ = function (selector) {
return new jQuery(selector);
};
// 测试代码
$('#div1').html('你好').addClass('cc dd bb').removeClass('bb').css({
'color': '#f00', 'font-size': '20px'});
复制代码
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/107113.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...