This article describes the method of implementing Excel tables with less than 30 lines of JS code. It can be seen that jQuery is not irreplaceable. Share it for your reference. The specific analysis is as follows:
A foreign programmer demonstrated an Excel table application written by native JS and does not rely on third-party libraries, with the following features:
① Implemented by less than 30 lines of native JavaScript code
② No dependency on third-party libraries
③ Excel-style semantic analysis (the formula begins with "=")
④ Support any expression (=A1+B2*C3)
⑤ Prevent circular references
⑥ Automatic local persistent storage based on localStorage
The effect display is shown in the figure below:
Code analysis:
CSS is omitted, HTML core is only one line:
Copy the code as follows: <table></table>
The JavaScript code is as follows:
Copy the code 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.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, through the above article, we can see that the most core steps use the features of EMEAScript5 and HTML5, such as:
querySelectorAll: provides query similar to jQuery selectors. It can be seen that third-party JS libraries such as jQuery are not necessarily a large number.
The code copy is as follows: var matches = document.querySelectorAll("div.note, div.alert");
defineProperty provides classes with Java's get and set access/set preprocessing methods, as well as some other configuration properties, such as: whether it is configurable, enumerable, etc.
The code copy is as follows:Object.defineProperty(o, "b", {get : function(){ return bValue; },
set : function(newValue){ bValue = newValue; },
enumerable : true,
configurable : true});
I hope this article will be helpful to everyone's JavaScript programming.