JQuery遍历for循环与each方法

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>
复制代码

 

posted @   夫君  阅读(2072)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示