递归验证 HTML 个输入元素

Recursively validating HTML input elements

我编写了以下递归输入验证器,它适用于我。有没有更好的方法来访问每个 dom 元素并检查它是否是输入字段并验证它?

function formValidator(parent)
{
    //base case no children
    if( parent.children().length == 0)
        return

    //recurse through each childs' child
    parent.children().each(function(){
        formValidator($(this));

    /**
    * Work : check if this node is an input node
    */
        if($(this).is("input"))
        {
            var type = $(this).attr('type');

            if(type =="text")
              //do work bro

        }

   });//end for each

}

如果更好是指更简洁,那么这在功能上是等价的

parent.find('*').each(function(){
    /**
    * Work : check if this node is an input node
    */
        if($(this).is("input"))
        {
            var type = $(this).attr('type');

            if(type =="text")
              //do work bro

        }

   });//end for each

注意这里不需要递归,因为

parent.find('*')

使用 *(all-selector)。这将获取所有子项和嵌套子项。

更新

为了提高性能,您可以将以上重构为

parent.find('input[type="text"]').each(function(){
        var type = $(this).attr('type');

                //if(type =="text")
                  //above no longer needed
       });//end for each

这将获取所有嵌套的 input 元素,因此您甚至不必检查

if($(this).is("input"))

我会使用更窄的选择器:

parent.children().find("input:text").each(function(){
    // Valid $(this) element to validate
});