jQuery .each() 集合中的最后一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4006822/
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
Last element in .each() set
提问by Ryan
I have an issue, where by I am doing a simple form validation, that needs some custom stuff that the validation plugin could not do for me. Basically, I have a name, email and message field, all are required, but only email is really validated, the others just need to check if theyre not empty. Here is my current code:
我有一个问题,我在做一个简单的表单验证时,需要一些验证插件无法为我做的自定义内容。基本上,我有一个姓名、电子邮件和消息字段,所有这些都是必需的,但只有电子邮件真正经过验证,其他人只需要检查它们是否不为空。这是我当前的代码:
$("#contactMe form").submit(function() {
var email = $('.requiredEmail').val();
if(email != 0) {
if(isValidEmailAddress(email)) {
$('.requiredText').each(function() {
thisVal = $(this).val();
var $this = $(this);
if(thisVal != 0) {
console.log('Valid Field: '+thisVal);
if ($(this) == $(this).parent(':last')) {
console.log('Last field, submit form here');
}
}
});
} else {
console.log('Email Not Valid');
}
}
return false;
});
Just to explain, I am first checking the email address is valid via the isValidEmailAddress function, which is working. Then I am going through using each(), all the requiredText fields and checking if theyre not empty. When I get to the last requiredText field, I want to submit the form using post or whatever.
只是为了解释一下,我首先通过 isValidEmailAddress 函数检查电子邮件地址是否有效,该函数正在工作。然后我将使用 each(),所有 requiredText 字段并检查它们是否不为空。当我到达最后一个 requiredText 字段时,我想使用 post 或其他方式提交表单。
if ($(this) == $(this).parent(':last')) {
What I have there is obviously incorrect but I am not sure what can be used to check if it is the last in the each result set, and perform an action if true.
if ($(this) == $(this).parent(':last')) {
我所拥有的显然不正确,但我不确定可以使用什么来检查它是否是每个结果集中的最后一个,如果为真则执行操作。
Can anybody help me out here?
有人可以帮我吗?
Thanks in advance.
提前致谢。
回答by Jacob Relkin
each
passes into your function index
and element
. Check index
against the length of the set and you're good to go:
each
传入您的函数index
和element
. 检查index
集合的长度,您就可以开始了:
var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
thisVal = $(this).val();
if(parseInt(thisVal) !== 0) {
console.log('Valid Field: ' + thisVal);
if (index === (length - 1)) {
console.log('Last field, submit form here');
}
}
});
回答by Ergec
For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.
对于未来的 Google 员工,我有不同的方法来检查它是否是最后一个元素。它类似于 OP 问题中的最后一行。
This directly compares elements rather than just checking index numbers.
这直接比较元素,而不仅仅是检查索引号。
$yourset.each(function() {
var $this = $(this);
if($this[0] === $yourset.last()[0]) {
//$this is the last one
}
});