I'm calling the below 2 function once per Cell in a table with over 135 columns and over 200 rows (that is 134*200 = 26800
times, I'm not running the functions on the first column).
I would like to optimize the functions as much as possible. Do you have any suggestions on how to do that, if it even possible?
this.addBodyCellFunction = function(row, index, func, params) {
var cell = $(document.getElementById("table_row_" + row +"_col_" +index));
cell.click(function() {
func.apply(this, params);
});
cell.css("cursor", "pointer");
};
this.addBodyCellTooltip = function(row, index, text) {
var cell = $(document.getElementById("table_row_" + row +"_col_" +index));
cell.attr("title", text);
};
2 Answers 2
There a few options here, for instance you don't need to use Jquery as much as you are using. This will optimize greatly all of your code.
You can simply use JavaScript commands related to table with document.getElementById("table").rows[].cell[]
which is very simple and works very nicely and fast. By doing that there is no need to assign ID's to everything on the table, as you probably are doing now.
-
\$\begingroup\$ Just because the question missuses jQuery, that is no reason to shift to raw Javascript. A delegated event will do a much better job (which is much harder to write in raw javascript). \$\endgroup\$TrueBlueAussie– TrueBlueAussie2014年10月01日 14:18:41 +00:00Commented Oct 1, 2014 at 14:18
-
\$\begingroup\$ Very true. That would be indeed a more elegant approach. \$\endgroup\$Luan E. Ferreira– Luan E. Ferreira2014年10月01日 14:28:35 +00:00Commented Oct 1, 2014 at 14:28
So, the big one looks like it would switching to one delegate instead of binding a listener to every cell.
Assuming that each $(document.getElementById("table_row_" + row +"_col_" +index))
represents a cell, this should work fine:
$(table).on('td', 'click', function(){func.apply(this, params);})
As to
var cell = $(document.getElementById("table_row_" + row +"_col_" +index));
cell.attr("title", text);
You can get rid of the $
and use plain JS:
// you can also use the document.getElementById("table").rows[].cell[]
// method that Luan suggested.
var cell = document.getElementById("table_row_" + row +"_col_" +index);
cell.setAttribute('title', text)
cell.css
. \$\endgroup\$.rows
collection on thetable
and thecells
collection on therow
... like:document.getElemntById("my_table").rows[1].cells[3]
\$\endgroup\$cell.setAttribute("title", text)
. \$\endgroup\$