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:
输出当前数组中每个元素的平方
var array = [1,2,3]
    mui.each(array,function(index,item){
      console.log(item*item);
    });

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

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

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

<div class="mui-input-group">
  <div class="mui-input-row">
    
    "text" class="mui-input-clear" id="col1" placeholder="请输入">
  div>
  <div class="mui-input-row">
    
    "text" class="mui-input-clear" id="col2" placeholder="请输入">
  div>
  <div class="mui-input-row">
    
    "text" class="mui-input-clear" id="col3" placeholder="请输入">
  div>
div>

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

var check = true;
mui(".mui-input-group input").each(function () {
  //若当前input为空,则alert提醒
  if(!this.value||trim(this.value)==""){
    var label = this.previousElementSibling;
    mui.alert(label.innerText+"不允许为空");
    check = false;
    return false;
  }
});
//校验通过,继续执行业务逻辑
if(check){
  //.....
}

你可能感兴趣的:(html)