【问题标题】:Simple js framework, DOM. (module style, trying to make it like jQuery-style)简单的js框架,DOM。 (模块风格,试图让它像 jQuery 风格)
【发布时间】:2017-12-06 22:31:57
【问题描述】:

这只是一个训练练习。 为了解决这个问题,我使用 material

编写了这样的脚本
    (function(window) {
    function smp(selector) {
    return new smpObj(selector);
    }

    function smpObj(selector) {
        this.length = 0;
        if (!selector ) {
            this.el = [];
            return this;
            }
        if (selector.nodeType ) {
            this.el = selector;
            this.length = 1;
            return this;
        } else 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.lenghth=this.el.length
            return this;
        }
        else return null;
    }
 })(window);

然后我尝试这样调用:

smp('body');

但浏览器找不到我的 smp 定义。
将来我想添加一些方法来使用它(例如,改变颜色):

 smp('.myClass').method('attr')

如果有人能告诉我我的错误,我将不胜感激。

更新: 添加方法仍然存在一些问题,例如:

  smp('.myClass').method('attr') 

我试过这样:

  (function color(smp) {
    window.smp.prototype.changeColor = function() {
        for (var i = 0; i < this.length; i++) 
            this.el[i].style.color = color;
        return this;
    };
})(smp);

【问题讨论】:

  • selector 是一个字符串...字符串没有属性nodeType

标签: javascript html css dom frameworks


【解决方案1】:

您链接到的文章中的Module Export 部分对此进行了解释。

为了实际使用该函数,您需要将它分配给一个变量,无论是全局变量还是局部变量。您可以通过以下方式在本地执行此操作:

var smp = (...)(window)

但这意味着你必须在你的函数中返回一些东西。所以在你的代码末尾,在})(window) 返回smp 函数之前

return smpSelector

把它们放在一起:

var smp = (function(window) {

    function smpSelector(selector) {
      // ... snip
    }

    function smpObj(selector) {
      // ... snip
    }

    return smpSelector;

 })(window);

最后,如果您希望它在一个单独的文件中并且仍然可以访问smp,您可以全局分配它。事实上,大多数图书馆,包括jQuery,都是这样做的:

(function(window) {

    function smpSelector(selector) {
      // ... snip
    }

    function smpObj(selector) {
      // ... snip
    }

    window.smp = smpSelector

 })(window);

现在我们可以从不同的文件做:

 <script src="/path/to/smp/file"></script>
 var foo = smp('something')

【讨论】:

  • 哇,你的回答帮了很多忙,尤其是最新的编辑(那件事,我一开始就瞄准了)。想我现在明白了,真的很感激。
  • 继续编码我的朋友!
  • 我还有一个问题(添加方法)。不胜感激,如果你能检查一下。
  • 很乐意提供帮助,但我建议为它创建一个新问题,并且只写出与您现在正在做的事情相关的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
相关资源
最近更新 更多