Get the latest iteration in jquery every

I have the following code that I look at in the columns of tables, and if its last column I want it to do something else. Now it is hardcoded, but how can I change it so that it automatically recognizes its last column

$(this).find('td').each(function (i) { if(i > 0) //this one is fine..first column { if(i < 4) // hard coded..I want this to change { storageVAR += $(this).find('.'+classTD).val()+','; } else { storageVAR += $(this).find('.'+classTD).val(); } } }); 
+6
source share
4 answers

If you want to access the length inside the .each() callback, you just need to get the length in advance so that it is available in your area.

 var cells = $(this).find('td'); var length = cells.length; cells.each(function(i) { // you can refer to length now }); 
+10
source

It sounds like your goal is to make a list of values ​​separated by commas, why don't you collect the values ​​and use the 'join' array method?

 var values = [] $(this).find('td .' + classTD).each(function(i) { if (i > 0) values.push($(this).val()); }); storageVAR = values.join(','); 
+6
source

Something like this should do this:

 var $this = $(this), size = $this.size(); $this.find('td').each(function (index) { // FIRST if(index == 0) { } // LAST else if(index == size) { } // ALL THE OTHERS else { } }); 
+1
source

If all you want is the last column, you can use

 $(this).find('td:last') 

If you want to do something with other columns, go to

 $(this).find('td:last').addClass("last"); $(this).find('td').each(function() { if ($(this).hasClass("last")) { // this is the last column } else { // this isn't the last column } }); 

You can use data() instead of addclass() if you like it.

If everything you want to do does not have a comma at the end of the line, you can simply turn it off after:

 storageVAR = storageVAR.substr(0, (storageVAR.length - 1); 
-2
source

Source: https://habr.com/ru/post/907082/


All Articles