JQuery is not irreplaceable for Excel tables implemented by less than 30 lines of JS Code
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 from third-party Libraries
- Excel-style semantic analysis (the formula starts with "=)
- Any expression (= A1 + B2 * C3) is supported)
- Prevent loop reference
- LocalStorage-based Automatic local persistent Storage
Effect display:
Code Analysis:
CSS, HTML core only one line:
<table></table>
JavaScript code:
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.target.value = localStorage[e.target.id] || ""; }; elm.onblur = function(e) { localStorage[e.target.id] = e.target.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.
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.
Object.defineProperty(o, "b", {get : function(){ return bValue; }, set : function(newValue){ bValue = newValue; }, enumerable : true, configurable : true});
Original article jsfiddle.net