简体   繁体   English

每次在jquery中获取最后一次迭代

[英]get the last iteration in jquery each

I have the following code that I am going through the tables columns and if its the last column I want it to do something different. 我有以下代码,我将通过表列,如果它是最后一列,我希望它做一些不同的事情。 Right now its hard coded but how can I change so it automatically knows its the 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();
        }
    }
});

If you want access to the length inside the .each() callback, then you just need to get the length beforehand so it's available in your scope. 如果你想访问.each()回调中的长度,那么你只需要预先获得长度,这样你的范围就可以使用它。

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

It looks like your objective is to make a comma separated list of the values, why don't you collect the values and use the array method 'join'? 看起来你的目标是用逗号分隔值列表,为什么不收集值并使用数组方法'join'?

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

Something like this should do it: 这样的事情应该这样做:

var $this = $(this),
    size  = $this.length,
    last_index = size -1;

$this.find('td').each(function (index) { 

     if(index == 0) { 
         // FIRST

     } else if(index === last_index) {
         // LAST

     } else {
         // ALL THE OTHERS

     }

});

If all you want is the last column, you can use 如果你想要的只是最后一列,你可以使用

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

If you want to do things with other columns, go for 如果你想用其他列做事,那就去吧

$(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're comfortable with that. 如果您addclass()感到满意,可以使用data()而不是addclass()

If all you want to do is not have a comma at the end of your string, you could just chop it off afterward: 如果您想要做的就是在字符串末尾没有逗号,那么您可以随后将其删除:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM