.each()中的最后一个元素 [英] Last element in .each() set

查看:308
本文介绍了.each()中的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,即我正在做一个简单的表单验证,需要一些验证插件无法为我做的自定义内容.基本上,我有一个姓名,电子邮件和消息字段,所有都是必填项,但是只有电子邮件经过了真正的验证,其他人只需要检查它们是否为空即可.这是我当前的代码:

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;
});

仅说明一下,我首先通过isValidEmailAddress函数检查电子邮件地址是否有效,该功能正在运行.然后,我将使用each(),所有requiredText字段并检查它们是否不为空.当我到达最后一个requiredText字段时,我想使用post或其他方式提交表单.

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.

if ($(this) == $(this).parent(':last')) {我所拥有的显然是不正确的,但是我不确定可以用来检查它是否是每个结果集中的最后一个,如果是,则执行操作.

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.

有人可以在这里帮助我吗?

Can anybody help me out here?

先谢谢了.

推荐答案

each 传递给您的函数indexelement.对照集合的长度检查index,您就很好了:

each passes into your function index and element. Check index against the length of the set and you're good to go:

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');
          }
      }
});

这篇关于.each()中的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆