天天看点

Javascript知识【jQuery:数组遍历和事件】

  • 💂 个人主页:​​爱吃豆的土豆​​
  • 💬 如果文章对你有帮助、欢迎关注、点赞、收藏(一键三连)和订阅专栏哦
  • 🏆人必有所执,方能有所成!
  • 🌈欢迎加入社区,福利多多哦!​​土豆社区​​
  • 🐋希望大家多多支持😘一起进步呀!

目录

​​jQuery:数组遍历【阶段重点】​​

​​ jQuery:事件​​

jQuery:数组遍历【阶段重点】

<script>
     $(function(){
         var arr = ['a','b','c','d'];
         //js普通FOR循环遍历
        for(var i=0;i<arr.length;i++){
             console.log("索引:"+i+" 元素:"+arr[i]);
        }
         console.log("-----");
         //Jquery循环遍历1
        $(arr).each(function (index) {
             console.log("索引:"+index+" 元素:"+this);
        });
         console.log("-----");
         //Jquery循环遍历2
        $.each($(arr),function (index) {
             console.log("索引:"+index+" 元素:"+this);
        });
    });
</script>      
Javascript知识【jQuery:数组遍历和事件】

 建议使用第一种。

Javascript知识【jQuery:数组遍历和事件】

格式2:

function(index,n){
//index 为当前遍历的索引,从0开始
//n 就是this,为当前遍历出来的元素,这个元素是JS对象
}      

 jQuery:事件

Javascript知识【jQuery:数组遍历和事件】
<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
     <style>
         #d1{
             background-color: #87CEFA;
             width:300px;
             height:300px;
        }
         #d2{
             background-color:bisque;
             width:300px;
             height:300px;
        }
     </style>
     <script src="../js/jquery-3.3.1.min.js"></script>
     <script>
         $(function(){
             //页面加载完成时,
            //为d1加入鼠标移入和点击事件
            $("#d1").mouseover(function () {
                 //修改内容体为红色字体
                $(this).html("<font color='red'>我是div1</font>");
            }).click(function () {
                 alert(this.innerHTML);
            });
             //为d2加入鼠标移出事件
            $("#d2").mouseout(function () {
                 alert(this.innerHTML);
            });
        });
     </script>
</head>
<body>
     <div id="d1">我是div1</div>
     <div id="d2">我是div2</div>
</body>
</html>      

继续阅读