任务是以 jQuery 风格编写简单的框架,为了解决这个问题,我编写了代码:
(function(window) {
window.smp=function smpSelector(selector) {
return new smpObj(selector);
}
function smpObj(selector) {
this.length = 0;
if (!selector ) {
this.el = [];
return this;
}
if(typeof selector == 'string'){
if(selector[0]==='#'){
this.el = [document.getElementById(selector.slice(1, selector.length))];
this.length = 1;
return this;
} else if(selector[0]==='.'){
this.el = document.getElementsByClassName(selector.slice(1, selector.length));
this.length = this.el.length;
return this;
} else {
this.el = document.getElementsByTagName(selector);
this.length = this.el.length;
return this;
}
}
else return null;
}
window.smp.changeColor=function smpColor(color) {
for (var i = 0; i < this.length; i++)
this.el[i].style.color = color;
}
})(window);
而且它工作正常。我可以这样打电话:
smp('div')
但后来我尝试添加方法:
window.smp.changeColor=function smpColor(color) {
for (var i = 0; i < this.length; i++)
this.el[i].style.color = color;
}
而且它不能正常工作。
smp('div').changeColor('color')
(不能这样调用)
如果有人能告诉我错误,我将不胜感激。
我用过这篇文章article
最佳答案
由于您在 smpObj
函数中返回 this
,this
是 smpObj
的实例,而不是 window .smp
并且 smpObj
没有 changeColor
方法。
要让它工作,你可以这样做:
(function(window) {
window.smp = function smpSelector(selector) {
return new smpObj(selector);
};
function smpObj(selector) {
this.length = 0;
this.changeColor = function smpColor(color) {
for (var i = 0; i < this.length; i++) this.el[i].style.color = color;
};
if (!selector) {
this.el = [];
return this;
}
if (typeof selector == "string") {
if (selector[0] === "#") {
this.el = document.getElementById(selector.slice(1, selector.length));
this.length = 1;
return this;
} else if (selector[0] === ".") {
this.el = document.getElementsByClassName(
selector.slice(1, selector.length)
);
this.length = this.el.length;
return this;
} else {
this.el = document.getElementsByTagName(selector);
this.length = this.el.length;
return this;
}
} else return null;
}
})(window);
然后尝试
smp('div').changeColor('red')
关于javascript - 简单的js框架,DOM。 (模块样式,如 jQuery)添加方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44899057/