javascript - 简单的js框架,DOM。 (模块样式,如 jQuery)添加方法的问题

标签 javascript jquery html css frameworks

任务是以 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 函数中返回 thisthissmpObj 的实例,而不是 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/

相关文章:

javascript - 加载网站资源时出错(wordpress)

javascript - 为什么这个控制台记录两次?

html - 整个导航栏与下面的内容重叠

javascript - JQuery.each() : find elements containing input

Javascript - 简化一堆长重复的隐藏/显示功能

jquery - 为 React 渲染的同一个 div 类应用不同的颜色背景

javascript - 在javascript中用三元运算符连接字符串

javascript - 在表格单元格jquery中选择div

html - 在 IE 中清空 IMG SRC 触发注销

html - CSS 中的线程