简体   繁体   English

JavaScript-了解带有返回DOM元素的方法链接

[英]JavaScript - Understanding Method Chaining with return DOM elements

I'm trying to understand Javascript chaining with a return DOM element. 我试图了解带有返回DOM元素的Javascript链接。 I'm not sure how to do this. 我不确定该怎么做。

This is my code: 这是我的代码:

        (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;

        })();

Call Methods: 调用方法:

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

// Returns .. <div>

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

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

HTML: HTML:

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

I'm not sure why it would give me a TypeError, I have the parentNode which is the div all I want to do is set the color text of that div. 我不知道为什么它会给我一个类型错误,我有parentNode这是所有我想要做的是设置div的彩色文本的股利

In order to make chainable methods available, you must not return a DOM element but rather an instance of your MyQuery class that has this method. 为了使可链接方法可用,您不得返回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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM