首页 > 其他分享 >JQuery遍历for循环与each方法

JQuery遍历for循环与each方法

时间:2023-02-11 10:44:26浏览次数:40  
标签:JQuery index 遍历 element 循环 each alert

jQuery-遍历

  js的遍历方式

    for(初始化值;循环结束条件;步长)

   jq的遍历方式

    1. jq对象.each(callback)

      1. 语法:

      jquery对象.each(function(index,element){});

        index:就是元素在集合中的索引

        element:就是集合中的每一个元素对象

        this:集合中的每一个元素对象

      2. 回调函数返回值:

        true:如果当前function返回为false,则结束循环(break)。

        false:如果当前function返回为true,则结束本次循环,继续下次循环(continue)

    2. $.each(object, [callback])

    3. for..of: jquery 3.0 版本之后提供的方式

      for(元素对象 of 容器对象)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="../js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
/*

        遍历
            1. js的遍历方式
             * for(初始化值;循环结束条件;步长)
            2. jq的遍历方式
                1. jq对象.each(callback)
                2. $.each(object, [callback])
                3. for..of:jquery 3.0 版本之后提供的方式

*/
            $(function () {
               //1.获取所有的ul下的li
                var citys = $("#city li");
               /* //2.遍历li
                for (var i = 0; i < citys.length; i++) {
                    if("上海" == citys[i].innerHTML){
                        //break; 结束循环
                        //continue; //结束本次循环,继续下次循环
                    }
                    //获取内容
                    alert(i+":"+citys[i].innerHTML);

                }*/

/*
                //2. jq对象.each(callback)
                citys.each(function (index,element) {
                    //3.1 获取li对象 第一种方式 this
                    //alert(this.innerHTML);
                    //alert($(this).html());
                    //3.2 获取li对象 第二种方式 在回调函数中定义参数   index(索引) element(元素对象)
                    //alert(index+":"+element.innerHTML);
                    //alert(index+":"+$(element).html());

                    //判断如果是上海,则结束循环
                    if("上海" == $(element).html()){
                        //如果当前function返回为false,则结束循环(break)。
                        //如果返回为true,则结束本次循环,继续下次循环(continue)
                        return true;
                    }
                    alert(index+":"+$(element).html());
                });*/
                //3 $.each(object, [callback])
               /* $.each(citys,function () {
                    alert($(this).html());
                });*/

               //4. for ... of:jquery 3.0 版本之后提供的方式

                for(li of citys){
                    alert($(li).html());
                }


            });


    </script>
</head>
<body>
<ul id="city">
    <li>北京</li>
    <li>上海</li>
    <li>天津</li>
    <li>重庆</li>
</ul>
</body>
</html>

 

标签:JQuery,index,遍历,element,循环,each,alert
From: https://www.cnblogs.com/xuche/p/17110987.html

相关文章