我编写了以下递归输入验证器,它适用于我。有没有更好的方法来访问每个 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"))
关于javascript - 递归验证 HTML 输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30359704/