简体   繁体   English

类似于jQuery的结构-ES6 JS链接

[英]jQuery like structure - ES6 JS Chaining

This is my first post on StackOverflow, so at beginning I'm sorry for my not full fluent English ;) But I try explain with what I have problem. 这是我在StackOverflow上的第一篇文章,所以一开始我为我的英语不流利而感到抱歉;)但是我尝试用我的问题进行解释。

Here is live example 这是现场示例

http://codepen.io/anon/pen/JKGbdE 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> 

If you open browser console you will see something like this: 如果打开浏览器控制台,您将看到以下内容:

[Log] first ex: – [日志]首先是:–

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

[Log] second ex: – [日志]秒前:–

<body>…</body>

The second example is OK. 第二个示例是OK。 I just want to return a HTML node. 我只想返回一个HTML节点。 In the first example it should return only <div id="el /> . 在第一个示例中,它应该仅返回<div id="el />

Any suggestions? 有什么建议么?

In first ex: you are returning new S(...) and in second ex: - this.nodes (DOM objects). first ex: this.nodes first ex:您将返回new S(...)second ex: this.nodes second ex: this.nodes (DOM对象)。

Unless you extend JS DOM manipulation, you cannot expect getting DOMObject as response with all subfunctions working - jQuery also cannot give you this possibility. 除非您扩展JS DOM操作,否则您不能指望在所有子功能都起作用的情况下获得DOMObject作为响应-jQuery也无法给您这种可能性。

Try console.log(jQuery('.anything')) - it also returns an object that has DOM object as item (with index 0 to be exact). 尝试console.log(jQuery('.anything')) -它还返回一个对象,该对象具有DOM对象作为项目(确切的索引为0)。

You should change your code so it will always return S object. 您应该更改代码,使其始终返回S对象。

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

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