簡體   English   中英

類似於jQuery的結構-ES6 JS鏈接

[英]jQuery like structure - ES6 JS Chaining

這是我在StackOverflow上的第一篇文章,所以一開始我為我的英語不流利而感到抱歉;)但是我嘗試用我的問題進行解釋。

這是現場示例

http://codepen.io/anon/pen/JKGbdE

 class S { constructor(selectors) { let self = this; this.elements(selectors); } elements(selectors) { this.selectors = selectors; let result = document.querySelectorAll(this.selectors); if( result.length == 1 ) { result = result[0]; this.element = result; } else { this.elements = [].slice.call(result); } this.nodes = result; return this.nodes; } parent() { let self = this; if( !!this.element ) { this.nodes = this.element.parentNode; } else { this.elements.forEach = (item, key) => { self.elements[key] = item.parentNode; }; this.nodes = this.elements; } return this.nodes; } result(a) { return this.nodes; } } window.$ = (selectors) => { let el = new S(selectors); return el; }; console.log('first ex: ', $('#el') ) console.log('second ex: ', $('#el').parent() ) 
 <html> <body> <div id="el">test</div> </body> </html> 

如果打開瀏覽器控制台,您將看到以下內容:

[日志]首先是:–

S {selectors: "#el", element: <div id="el">, nodes: <div id="el">, …} 

[日志]秒前:–

<body>…</body>

第二個示例是OK。 我只想返回一個HTML節點。 在第一個示例中,它應該僅返回<div id="el />

有什么建議么?

first ex: this.nodes first ex:您將返回new S(...)second ex: this.nodes second ex: this.nodes (DOM對象)。

除非您擴展JS DOM操作,否則您不能指望在所有子功能都起作用的情況下獲得DOMObject作為響應-jQuery也無法給您這種可能性。

嘗試console.log(jQuery('.anything')) -它還返回一個對象,該對象具有DOM對象作為項目(確切的索引為0)。

您應該更改代碼,使其始終返回S對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM