Less than 30 lines of JS code can be used to implement Excel tables, and 30 lines of excel
The example in this article describes how to implement an Excel table using less than 30 lines of JS Code. It can be seen that jQuery is not irreplaceable. Share it with you for your reference. The specific analysis is as follows:
A foreign programmer shows an Excel table application written by native JS that does not rely on third-party libraries. It has the following features:
① Implemented by less than 30 lines of native JavaScript code
② Independent of third-party Libraries
③ Excel-style semantic analysis (the formula starts with "=)
④ Any expression supported (= A1 + B2 * C3)
⑤ Prevent circular references
⑥ Automatic local persistent Storage Based on localStorage
Shows the effect:
Code Analysis:
CSS, HTML core only one line:
Copy codeThe Code is as follows: <table> </table>
The JavaScript code is as follows:
Copy codeThe Code is as follows: for (var I = 0; I <6; I ++ ){
Var row = document. querySelector ("table"). insertRow (-1 );
For (var j = 0; j <6; j ++ ){
Var letter = String. fromCharCode ("A". charCodeAt (0) + J-1 );
Row. insertCell (-1). innerHTML = I & j? "": I | letter;
}
}
Var DATA ={}, INPUTS = []. slice. call (document. querySelectorAll ("input "));
INPUTS. forEach (function (elm ){
Elm. onfocus = function (e ){
E.tar get. value = localstoragee.tar get. id] | "";
};
Elm. onblur = function (e ){
Localstorage‑e.tar get. id] = e.tar get. value;
ComputeAll ();
};
Var getter = function (){
Var value = localStorage [elm. id] | "";
If (value. charAt (0) = "= "){
With (DATA) return eval (value. substring (1 ));
} Else {return isNaN (parseFloat (value ))? Value: parseFloat (value );}
};
Object. defineProperty (DATA, elm. id, {get: getter });
Object. defineProperty (DATA, elm. id. toLowerCase (), {get: getter });
});
(Window. computeAll = function (){
INPUTS. forEach (function (elm) {try {elm. value = DATA [elm. id];} catch (e ){}});
})();
In fact, we can see from the above that the core steps use EMEAScript5 and HTML5 features, such:
QuerySelectorAll: Provides queries similar to the jQuery selector. Therefore, a third-party JS Library such as jQuery is not required.
Copy codeThe Code is as follows: var matches = document. querySelectorAll ("div. note, div. alert ");
DefineProperty provides the Java get and set access/set preprocessing methods for classes, as well as other configuration attributes, such as configuration or enumeration.
Copy codeThe Code is as follows: Object. defineProperty (o, "B", {get: function () {return bValue ;},
Set: function (newValue) {bValue = newValue ;},
Enumerable: true,
Retriable: true });
I hope this article will help you design javascript programs.