简体   繁体   English

如何使用JavaScript创建类似对象函数的jQuery

[英]How to create jQuery like object functions with JavaScript

I'm working on trying to create a small library of helper functions for a project. 我正在尝试为项目创建一个小的辅助函数库。

At the moment, I've setup a lot of functions in global scope that look like this: 目前,我已经在全局范围内设置了许多如下所示的函数:

function addClass(el, className) {
   el.classList.add(className);
}

var target = document.querySelector('.target);
addClass(target, "added-class");

With adding a class as an example, I'd like to follow a jQuery like function so that it gets called like this: 以添加一个类为例,我想遵循一个类似jQuery的函数,以便像这样被调用:

var target = document.querySelector('.target);
target.addClass("added-class");

How can I setup a function so that it is called this way? 如何设置一个函数,使其以这种方式调用?

You could extend HTMLElement 您可以扩展HTMLElement

As @charlietfl mentioned, extending native API works fine in theory but should also be concerned that future specifications in HTMLElement could add similar methods that open the app up to potential collisions. 正如@charlietfl提到的那样, 扩展本机API在理论上可以正常工作,但还应担心,HTMLElement中的未来规范可能会添加类似的方法,从而使应用程序容易发生潜在的冲突。

Like this example: 像这个例子:

 function addClass(className) { this.classList.add(className); } // here you extends HTMLElement prototype HTMLElement.prototype.addClass = addClass; var target = document.getElementById('mydiv'); target.addClass('red'); var target2 = document.getElementById('mydiv2'); target2.addClass('blue'); 
 .red { background: red; } .blue { background: blue; } 
 <div id="mydiv">HELLO</div> <div id="mydiv2">WORLD</div> 

Or Could use a Wrapper 或可以使用包装纸

Like this another example: 像这样另一个例子:

 function Element(id) { this.target = document.getElementById(id); this.addClass = function (className) { this.target.classList.add(className); } return this; } var target =new Element('mydiv'); target.addClass('red'); var target2 =new Element('mydiv2'); target2.addClass('blue'); 
 .red { background: red; } .blue { background: blue; } 
 <div id="mydiv">HELLO</div> <div id="mydiv2">WORLD</div> 

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

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