jQuery each() 方法

时间:4年前   阅读:5208

一、$(selector).each(function(index, element) {})方法遍历一个jquery对象,为每一个匹配的元素运行定义的函数。

index: 选择器的index位置。

element: 当前的元素。

二、$.each()用于迭代数组和对象。数组和类似数组的对象通过一个长度属性来迭代数字索引,从0到length-1。其他对象通过其属性名进行迭代。

$.each(array, function(index, value) {})

数组的回调函数每次传递一个索引和相应的数组值作为参数。

对象的回调函数每次传递一个键值对。

如果要终止迭代返回false;

返回非false相当于continue跳出当前迭代,转到下一个迭代。

使用jQuery.each()函数迭代对象或数组,jQuery示例代码如下: 

// 遍历数组元素

$.each( [1, 2, 3] , function(i, item){

    alert("索引=" + i + "; 元素=" + item);  

} );

// 遍历对象属性

$.each( { name: "张三", age: 18 } , function(property, value){

    alert("属性名=" + property + "; 属性值=" + value);    

} );

var array = [];

array[2] = "Code";

array[4] = "Player";

// 会遍历索引为0、1、2、3、4的元素,其中0、1、3的元素是undefined

$.each( array , function(i, item){

    alert("索引=" + i + "; 元素=" + item);  

} );

jQuery.each()函数同样可以遍历jQuery对象中匹配的元素,以下面这段HTML代码为例:

<div id="n1">

    <div id="n2">

        <ul id="n3">

            <li id="n4">item1</li>

            <li id="n5">item2</li>

            <li id="n6">item3</li>

        </ul>

    </div>  

</div>

<form id="demoForm">

    <input name="goods_weight" type="checkbox" value="20">A(20kg)<br>

    <input name="goods_weight" type="checkbox" value="33">B(33kg)<br>

    <input name="goods_weight" type="checkbox" value="36">C(36kg)<br>

    <input name="goods_weight" type="checkbox" value="49">D(49kg)<br>

    <input name="goods_weight" type="checkbox" value="56">E(56kg)<br>

    <input name="goods_weight" type="checkbox" value="78">F(78kg)<br>

    <input id="btnBuy" type="button" value="订购">    

</form>

现在,我们将所有的<li>元素的innerHTML改为"编号n"(n为1、2、3……)。

$.each( $("ul li"), function(index, element){

    // this === element

    $(element).html( "编号" + (index + 1) );  

});

接着,我们注册【订购】按钮的点击事件,用于处理商品订购事务,要求每次订购的商品重量不得超过100kg,否则无法订购并提示相应信息。

$("#btn").click(function(){

    var weight = 0;

    $.each( $("[name=goods_weight]:checked"), function(){

        weight += parseInt(this.value);

        if(weight > 100){

            return false;

        }

    });

    if(weight <= 0){

        alert("没有选择任何商品!");

    }else if(weight > 100){

        alert("一次订购的商品重量不能超过100kg!");

    }else{

        // 订购商品

        alert("订购商品成功!");

    }

});

本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。

微信扫码关注

更新实时通知

上一篇:为什么你的50ETF期权还在亏损?

下一篇:期权招商代理是什么意思?做代理有什么优势?

网友评论

请先 登录 再评论,若不是会员请先 注册