Simulate jquery
1. First simulate a jquery object named XJS here, as shown belowCode:
VaR XJS = function (selector) {return document. getelementbyid (selector);} alert (XJS ("d1"). innerhtml );
But now a DOM object is returned through XJS, which is different from a jquery object returned by jquery. In order for XJS to return itself, XJS needs to be expanded.
VaR XJS = function (selector) {return XJS. FN. INIT (selector );}
XJS. fn = XJS. prototype = {init: function (selector) {If (typeof selector = "string") {This [0] = document. getelementbyid (selector); return this ;}}}
The above Code does not check the validity of selector, so it is regarded as a valid ID. As the code above extends the XJS object and returns it through XJS. FN. init, the object I get through XJS ("") is an XJS object.
2. Create a simple alias for XJS, such as $
Window. $ = Window. XJS = XJS;
In this way, you can use $ ("") directly.
3. Prevent name conflicts
(Function () {var XJS = function (selector) {return XJS. FN. init (selector);} XJS. fn = XJS. prototype = {init: function (selector) {If (typeof selector = "string") {This [0] = document. getelementbyid (selector); return this ;}} window. $ = Window. XJS = XJS ;})();
4.xjs.html ()
Because the objects returned through $ or XJS are already their own, to use JS attributes or methods such as innerhtml, you must convert XJS objects to DOM objects. So you can implement your own methods like jquery.
(Function () {XJS. fn = XJS. prototype = {init: function (selector) {If (typeof selector = "string") {This [0] = document. getelementbyid (selector); return this ;}}, HTML: function () {If (arguments. length = 0) {return this [0]. innerhtml;} else {This [0]. innerhtml = arguments [0] ;}, version: "8.8.8 "}
If no parameter is input, the HTML content of the object is obtained. If the parameter is input, the HTML of the object is set to the input value.
In order to make the XJS Instance Object inherit the methods and attributes in the initial XJS prototype, The XJS prototype is assigned to the XJS object.
XJS. FN. init. Prototype = XJS. FN;
In this way, you can obtain the version attribute in the following format.
Alert (T. version );
So far, a simple simulated XJS is complete. The complete code is as follows:
(Function () {var XJS = function (selector) {return XJS. FN. init (selector);} XJS. fn = XJS. prototype = {init: function (selector) {If (typeof selector = "string") {This [0] = document. getelementbyid (selector); return this ;}}, HTML: function () {If (arguments. length = 0) {return this [0]. innerhtml;} else {This [0]. innerhtml = arguments [0] ;}, version: "8.8.8"} XJS. FN. init. prototype = XJS. FN; window. $ = Window. XJS = XJS ;})();
After the above JS file is introduced in the page, it can be used as below
VaR T = $ ("d1"); t.html ("hello"); alert(t.html (); alert (T. version );
The preceding d1 is the ID of an HTML element.