在jQuery中,我会这样做:
var foo = jQuery("form");
foo.each(function(){
this.find(".required").each(function(){...})
})
这将在当前处理的表单中找到每个必填字段。
但是当我不得不使用Dojo时,我有点迷失了。在Dojo中,您需要使用dojo.forEach()
var foo = dojo.query("form");
dojo.forEach(foo, function(self,i){
// And now I have no idea on what to use the forEach.
// The "self" parameter is the form node. So now I
// would need something like `self.forEach`
// But that obviously does not work
}
您只需要像在第一级中一样再次进行另一个查询。 Dojo的哲学是,事情通常比jQuery中的“魔术”少。
var forms = dojo.query("form"); //No second argument; Searches whole document
dojo.forEach(forms, function(form){
var requireds = dojo.query(".required", form);//Only search under
// the current form.
dojo.forEach(requireds, function(required){
/* do stuff*/
});
})
我还自由更改了自变量的名称(因为与jQuery不同,Dojo不会更改this
),并从forEach中删除了可选的i
参数。
请注意,您本可以使用dijit.form.Form并节省很多检查麻烦;)另外,您可以直接使用:
而不是嵌套forEachdojo.query("form *.required").forEach(function(requiredNode){}, this);
甚至(但尚未经过测试)
dojo.query("form .required").forEach(function(requiredNode){}, this);