Javascript 递归验证HTML输入元素

Javascript 递归验证HTML输入元素,javascript,jquery,html,recursion,Javascript,Jquery,Html,Recursion,我已经编写了下面的递归输入验证器,它适合我。是否有更好的方法访问每个dom元素,检查它是否是输入字段并验证它 function formValidator(parent) { //base case no children if( parent.children().length == 0) return //recurse through each childs' child parent.children().each(function(){

我已经编写了下面的递归输入验证器,它适合我。是否有更好的方法访问每个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('*')
使用。这将获取所有子级和嵌套子级

更新

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

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

这个问题可能更适合你,因为你的问题的本质是寻求改进,而不是帮助解决问题。我可以把我的帖子移到那里吗?或者有人可以帮我移到那里吗?你可以在这里删除你的帖子并在那里重新发布(首选),或者标记它以引起版主的注意,要求迁移它(可能会避免这样做,因为对于过度工作的版主来说,这需要更多的工作)现在你有了一个答案,我不认为你可以删除它。我喜欢这个答案,但我有点好奇哪一个更有效。你可以避免
类型
检查
家长。查找('input:text')…
@RickHitchcock,非常好的观察!更新了我的答案。谢谢这不包括作为父对象的直接子对象的输入,OP的代码处理这些子对象(
if($(This).is(“输入”))
)。您可以通过删除
children()
方法来修复它。