本文介绍了为什么我用于检查必需输入字段的jQuery脚本这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery检查无法识别required HTML标记的浏览器的必填输入字段.我的jQuery脚本如下.

I am trying to use jQuery to check for required input fields for browsers that don't reccognise the required HTML tag. My jQuery script is as follow.

$('div').on('submit', '#myform', function(e){
    e.stopPropagation();
    e.preventDefault();
    $( ':input[required]').each( function (e) {
        if ( this.value.trim() == '' ) {
            $('.error').html(this.name + " is required");
            return false;
        }
    });
    $(this).unbind().submit();
 });

但是加载非常慢!在单击表单的提交"按钮后,大约需要5秒钟才能显示错误信息!似乎正在循环.为什么会这样呢?我该如何解决?

But it is very slow to load! after I click the submit button for the form, it takes about 5 seconds before the error messahe shows! It seems it is taking some loops. Why is it that? How can I solve this?

推荐答案

委托的submit处理程序未直接绑定到form元素,因此您无法以这种方式取消绑定处理程序.您正在创建一个无限循环.您应该使用off方法并取消绑定div元素的处理程序.

The delegated submit handler is not bound directly to the form element so you can't unbind the handler that way. You are creating an infinite loop. You should use the off method and unbind the handler of the div element.

还请注意,each回调的返回值不会影响包装程序,提交处理程序的运行流程.每个函数都有其自己的返回值.

Also note that the returned value of the each callback doesn't affect run flow of the wrapper, submit handler. Each function has it's own returned value.

$('div').on('submit', '#myform', function(e){
    var $e = $('.error').empty();
    var $invalids = $(':input[required]').filter( function (e) {
        var invalid = this.value.trim().length === 0;
        if ( invalid ) {
            $e.append('<p>' + this.name + " is required</p>");
        }
        return invalid;
    });
    if ( $invalids.length ) {
       return false;
    }
    this.submit();
});

HTMLFormElement对象的submit方法不会触发jQuery提交处理程序,因此无需取消绑定处理程序.如果验证通过,则表单将正常提交.

The submit method of HTMLFormElement object doesn't trigger jQuery submit handler so there is no need to unbind the handler. If the validation passes the form is submitted normally.

在性能方面,您也可以避免使用:input选择器.从jQuery :input文档:

Performance-wise you can also avoid using :input selector. From jQuery :input documentation:

elements 属性c6>对象在HTML5浏览器中返回 HTMLFormControlsCollection 对象, HTML4浏览器中的HTMLCollection对象,其中包含form元素的所有控件.您也可以使用此属性代替查询DOM,并使用jQuery filter方法过滤required字段:

The elements property of the HTMLFormElement object returns a HTMLFormControlsCollection object in HTML5 browsers and a HTMLCollection object in HTML4 browsers that contains all the controls of the form element. You could also use this property instead of querying the DOM and use the jQuery filter method for filtering required fields:

 $(this.elements).filter('[required]');

这篇关于为什么我用于检查必需输入字段的jQuery脚本这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 17:01