簡體   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