繁体   English   中英

JavaScript链接返回未定义

[英]Javascript Chaining return undefined

我有这个OOP作品的问题。 基本上,此$("notfound")不在文档中。 它放了一个错误。 但是如果将其更改为$("parent")则可以正常运行,因为它在文档中。

检查这个小提琴:

https://jsfiddle.net/k6j70f1h/8/

在console.log中,子项未定义。

如何得到这个东西的作品?

我的代码有什么问题?

 "use strict" var $, i; (function() { $ = function(el, context) { context = context || document; return new obj$(el, context); }; var obj$ = function(el, context) { var cl = context.getElementsByClassName(el), loop = cl.length; this.length = loop; for (i = 0; i < loop; i++) { this[i] = cl[i]; } }; obj$.prototype = { find : function(el) { if (this.length == 1) { return $( el, this[0] ); } }, css : function(obj, data) { if (this.length == 1) { this[0].style[obj] = data; return this; } } }; })(); var parent = $("notfound"), // this one cause error child = parent.find("child"); // throw an error child is undefined child.css("color", "orange"); parent.css("color", "purple"); 
 <div class="parent">parent <div class="child">child</div> </div> 

您所说的导致错误的行没有引起错误。

导致错误的行是:

child.css("color", "orange");

引起错误的原因是此行:

var parent = $("notfound"),

...返回length == 0parent对象,因此此行:

child  = parent.find("child"); // throw an error child is undefined

...电话find一个对象,其中上this.length不是1 ,所以在代码中find不进入体内的的if声明,你不返回任何东西。 这意味着调用parent.find(...)导致undefined ,您已将其分配给child 因此, child.css(...)尝试在undefined上调用css

如果您想制作类似jQuery的内容,则需要添加

return $();

...查找parent.find如果this.length为0(至少):

find : function(el) {
    if (this.length == 1) {
        return $( el, this[0] );
    }
    return $();
}

同样,如果您想模拟jQuery,则总是希望从css函数return this值,而不仅仅是具有一个元素。

这是具有最少必要更改的更新:

 "use strict" var $, i; (function() { $ = function(el, context) { context = context || document; return new obj$(el, context); }; var obj$ = function(el, context) { var cl = context.getElementsByClassName(el), loop = cl.length; this.length = loop; for (i = 0; i < loop; i++) { this[i] = cl[i]; } }; obj$.prototype = { find : function(el) { if (this.length == 1) { return $( el, this[0] ); } return $(); // Added }, css : function(obj, data) { if (this.length == 1) { this[0].style[obj] = data; } return this; // Moved } }; })(); var parent = $("notfound"), // this one cause error child = parent.find("child"); // throw an error child is undefined child.css("color", "orange"); parent.css("color", "purple"); 
 <div class="parent">parent <div class="child">child</div> </div> 

暂无
暂无

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

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