jQuery-遍历

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 容器对象)

02-遍历.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery遍历</title>
    <script src="../js/jquery-3.6.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>
posted @ 2023-02-15 15:10  肥宅快乐水~  阅读(32)  评论(0编辑  收藏  举报