【问题标题】:JavaScript - Understanding Method Chaining with return DOM elementsJavaScript - 理解带有返回 DOM 元素的方法链
【发布时间】:2016-02-07 17:25:07
【问题描述】:

我试图理解带有返回 DOM 元素的 Javascript 链接。 我不知道该怎么做。

这是我的代码:

        (function () {
            function MyQuery(selector) {
                if (!(this instanceof MyQuery)) {
                    return new MyQuery(selector);
                }

                this.nodes = document.querySelectorAll(selector);

                for (var i = 0; i < this.nodes.length; i++) {
                    this.nodes[i] = this.nodes[i];
                }

            }

            MyQuery.fn = MyQuery.prototype = {
                parent: function () {
                    return this.nodes[0].parentNode;
                },
                color: function(setColor) {
                    this.nodes[0].style.color = setColor;
                    return this;
                }
            };

            window.myQuery = window.$ = MyQuery;

        })();

调用方法:

myQuery(".mySpan").parent(); 

// Returns .. <div>

myQuery(".mySpan").parent().color("red");

// TypeError: myQuery(...).parent(...).color is not a function

HTML:

    <div>
        This DIV has some content.
        <span class="mySpan">This is a span</span>
        more content here.
    </div>

我不知道为什么它会给我一个 TypeError,我有一个父节点,它是 div 我想要做的就是设置那个 div 的颜色文本。

【问题讨论】:

  • this.nodes[i] = this.nodes[i]; - 等等什么?
  • 你可能想return new MyQuery(this.nodes[0].parentNode);在父...

标签: javascript methods prototype chaining method-chaining


【解决方案1】:

为了使可链接的方法可用,您必须返回 DOM 元素,而是返回具有此方法的 MyQuery 类的实例。

function MyQuery(selector) {
    if (!(this instanceof MyQuery)) {
        return new MyQuery(selector);
    }

    if (Array.isArray(selector)) {
        this.nodes = selector;
    } else {
        this.nodes = [];
        if (typeof selector == "string") {
            var nodes = document.querySelectorAll(selector);
            for (var i = 0; i < nodes.length; i++) {
                this.nodes[i] = nodes[i];
            }
        }
    }
}

MyQuery.prototype.parent = function () {
    return new MyQuery([this.nodes[0].parentNode]);
};
MyQuery.prototype.color = function(setColor) {
    this.nodes[0].style.color = setColor;
    return this;
};

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多