mui中的遍历each()

each()

each既是一个类方法,同时也是一个对象方法,两个方法适用场景不同;换言之,你可以使用mui.each()去遍历数组或json对象,也可以使用mui(selector).each()去遍历DOM结构。

第一种:

语法:
mui.each(obj,handler);

obj
Type: Array||JSONObj
需遍历的对象或数组;若为对象,仅遍历对象根节点下的key
handler
Type: Function( Integer||String index,Anything element)
为每个元素执行的回调函数;其中,index表示当前元素的下标或key,element表示当前匹配元素

example:
输出当前数组中每个元素的平方

1 var array = [1,2,3]
2 mui.each(array,function(index,item){
3      console.log(item*item);
4 });

第二种:
语法:
mui(selector).each(handler);

handler
Type: Function( Integer index,Element element)
为每个匹配元素执行的回调函数;其中,index表示当前元素在匹配元素中的位置(下标,从0开始),element表示当前匹配元素,可用this关键字代替

example:
当前页面中有三个字段,如下:

 1 <div class="mui-input-group">
 2   <div class="mui-input-row">
 3     <label>字段1:</label>
 4     <input type="text" class="mui-input-clear" id="col1" placeholder="请输入">
 5   </div>
 6   <div class="mui-input-row">
 7     <label>字段2:</label>
 8     <input type="text" class="mui-input-clear" id="col2" placeholder="请输入">
 9   </div>
10   <div class="mui-input-row">
11     <label>字段3:</label>
12     <input type="text" class="mui-input-clear" id="col3" placeholder="请输入">
13   </div>
14 </div>

提交时校验三个字段均不能为空,若为空则提醒并终止业务逻辑运行,使用each()方法循环校验,如下:

 1 var check = true;
 2 mui(".mui-input-group input").each(function () {
 3   //若当前input为空,则alert提醒
 4   if(!this.value||trim(this.value)==""){
 5     var label = this.previousElementSibling;
 6     mui.alert(label.innerText+"不允许为空");
 7     check = false;
 8     return false;
 9   }
10 });
11 //校验通过,继续执行业务逻辑
12 if(check){
13   //.....
14 }
原文地址:https://www.cnblogs.com/lgx5/p/15072070.html