【发布时间】: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