脑课堂编程教育

如何在项目中使用jQuery内each方法

Javascript 4年前
80 0 0
脑课堂编程培训

这次给大家带来如何在项目中使用jQuery内each方法,在项目中使用jQuery内each方法的注意事项有哪些,下面就是实战案例,一起来看一下。

概述:

  each() 方法规定为每个匹配元素规定运行的函数。

  返回 false 可用于及早停止循环,相当于break。

  返回 true 可以结束本次循环,相当于continue。

语法:

$(selector).each(function(index,element){ })    
    index - 选择器的 index 位置    
    element - 当前的元素(也可使用 "this" 选择器) 
    $(selector).each(function(){ })  
    $.each(array,function(Key,Value){ })

1.遍历js数组

$(function(){
    var array=["aaa","bbb","ccc"];
    $.each(array,function(i,j){  
        alert(i+":"+j);  //i表示索引,j代表值 
    });
})

2.遍历Object对象

var obj = new Object();obj.name="zs";
$.each(obj, function(name, value)
       {  
    alert(this);  //this指向当前属性的值,等价于value  
    alert(name);  //name表示Object当前属性的名称  
    alert(value);  //value表示Object当前属性的值
});

3.遍历JSON对象

var json ={"name":"zhangSan","role":"student"};
$.each(json,function(key,value)
       { 
    alert(key+":"+value);
});

4.遍历由多个JSON对象组成的数组

var json =[{"name":"Amy","role":"student"},{"name":"Tom","role":"student"}];
$.each(json, function(index, value) {  
    alert("index="+index+"\n" +"name:"+value.name+"\n"+"role:"+value.role+"\n");});

5.遍历jQuery对象 

<head>    
    <meta charset="utf-8" />  
        <title>遍历jQuery对象</title>  
<script src="js/jquery-1.12.4.js"></script> 
<script type="text/javascript">   
    $(function(){    
    $("input[type='button']").bind("click",function(){     
        $("li").each(function(){     
            alert($(this).text())     
        });   
    }); 
});  
</script>
</head> 
<body>  
    <input type="button" value="触发事件"/> 
        <ul>  
           <li>first</li>  
           <li>second</li> 
       </ul> 
</body>

相信看了本文案例你已经掌握了方法,更多精彩请关注脑课堂网站其它相关文章!

收藏

本文标题:如何在项目中使用jQuery内each方法

本文链接:https://naoketang.com/p/xm079l3g7prk

评论区

推荐课程