javascript 获取 jquery 中的最后一次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9041887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get the last iteration in jquery each
提问by Asim Zaidi
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();
}
}
});
回答by jfriend00
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
});
回答by loganfsmyth
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(',');
回答by Bj?rn Thomsen
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
}
});
回答by Grim...
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.
如果您对此感到满意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);