JavaScript入门学习案例

JavaScript入门学习案例

test01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS的引用方式</title>
    <style>
        div{
            width:100px;
            height:100px;
            background: #ccc;
        }
    </style>
    <!--1.内嵌方式-->
    <script>
        // alert("hello JavaScript");//弹出一个窗口
    </script>
    <!--3.引用外部的js脚本文件-->
    <script type="text/javascript" src="/js/hello.js">
        <!--在此处不可以再写js代码-->
    </script>
    <!--type="text/javascript"这个可以不写的-->
</head>
<body>
    第一个JavaScript程序
    <!--<script>-->
    <!--alert("hello JavaScript");//弹出一个窗口-->
    <!--</script> 写在body中也可以-->
    <hr>
    <!--2.内部方式-->
    <input type="button" value="点我" onclick="alert('我被点了,晕了!')">
    <div onmouseover="alert('走开')">把鼠标移上来!</div>
    <!--<a href="alert('超链接被触发!')">我是超链接</a> 这种方式不可以,它认
    为链接一个资源-->
    <a href="" onclick="alert('超链接被触发了!')">我是超链接</a>
    <a href="javascript:alert('超链接被触发了!')">我是超链接</a>
</body>
</html>

test02.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //变量
        var name;
        name = "tom";
        // name = 20;
        // name = 180.5;
        var age = 18;
        var 姓名="张无忌";
        //汉字也可以
        // var = var 这个不可以
        sex = "male"; // 强烈不建议
        var a=5,b=2,c=7;
        {
            var x = 6;
// alert(a);
// alert(x);
            let y = 7;
        }
        alert(x);
        alert(y);
        alert(sex)
    </script>
</head>
<body>
</body>
</html>

test03.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //输出信息
        // alert("嘿嘿");
        // console.log("哈哈"); //通过开发人员工具的console窗口验证结果
        // document.write("嘻嘻")
        //输入
        // var name = prompt("请输入你的姓名:");
        // console.log(name);
        // var age = prompt("请输入你的年龄:");
        // console.log(age);
        // console.log(age+2);
        // console.log(typeof age);
        // age = Number(age);
        // console.log(age+2);
        //转义字符
        console.log("he\tllo \n world");
        console.log('wel\'come');
        //注释
        //单行注释
        /*
        这是多行注释
        这是多行注释
        */
    </script>
</head>
<body>
</body>
</html>

test04.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        * 数据类型
        */
        var name='tom';
        var age=18;
        var height=180.5;
        var flag=true;
        var hobby=null;
        var date = new Date();
        var arr = new Array();
        var sex;//当定义了变量,但是未赋值,则返回undefined
        // console.log(typeof name);
        // console.log(typeof age);
        // console.log(typeof height);
        // console.log("hello"-5); //返回NaN
        // console.log(typeof flag);
        // console.log(typeof hobby); //如果数据是null、Date、Array等,返回object
        // console.log(typeof date);
        // console.log(typeof arr);
        // console.log(typeof sex);
        /*
        * 类型转换
        */
        //1.转换为number
        var a = '12';
        console.log(typeof a);
        //方式一:使用Number()
        // a = Number(a);
        // a = Number('12.5');
        // a = Number('12abc');
        a = Number('abc12');
        // console.log(12,'aaa',4,6);
        // console.log(Number(a),typeof a);
        //方式二:使用parseInt()
        // a = parseInt('12');
        // a = parseInt('12.5');
        // a = parseInt('12abc');//按字符顺序进行解析
        // a = parseInt('abc12');
        // console.log(a,typeof a);
        //方式三:使用parseFloat()
        // a = parseFloat('12');
        // a = parseFloat('12.5');
        // a = parseFloat('12abc');//按字符顺序进行解析
        // a = parseFloat('abc12');
        // console.log(a,typeof a);
        // a = Number(true);//boolean在内存中使用数字表示,true为1,false为0
        // console.log(a,typeof a);
        /*
        * 转换为字符串
        */
        // var a = 12;
        // var a = true;
        // a = a+'';
        // console.log(a,typeof a);
        /*
        *转换为布尔
        */
        // var a = Boolean(0);
        // var a = Boolean('');
        // var a = Boolean(null);
        // var a = Boolean(undefined);
        // var a = Boolean(NaN);
        // var a = Boolean(4);
        // var a = Boolean('tom');
        var name = 'tom';
        if(name){
            console.log(a,typeof a);
        }
        console.log(a,typeof a);
    </script>
</head>
<body>

</body>
</html>

test05.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        * 算术运算符
        */
        var a = 5;
        var b = 3;
        var c = 'aaa'; // var c = 'aaa';
        var d = true;
        // console.log(a+b);
        // console.log(a-b);
        // console.log(a*b);
        // console.log(a/b);
        // console.log(a%b);
        // console.log(a**b); //a的b次方
        // console.log(a-c); //会自动将字符串c转换为数值
        // console.log(a++);//前缀自加减
        // console.log(a--);
        // console.log(++a);//后缀自加减
        // console.log(--a);
        /*
        * 比较运算符
        */
        // console.log(a>b);
        // console.log(a<b);
        // console.log(a>=b);
        // console.log(a<=b);
        // var a = 5;
        // var b ='5';
        // console.log(a==b);//只判断内容是否相等
        // console.log(a===b);//全等于,既要判断内容,也要判断数据类型
        // console.log(a+b);
        // console.log(a==d);//var a = 1;测试 true表示1 false表示0
        /*
        * 赋值运算符
        */
        // a = 8;
        // a +=2 ; //a=a+2
        // a-=2;
        // console.log(a);
        /*
        * 逻辑运算符
        */
        var x=true;
        var y=false;
        // console.log(x && y);
        // console.log(x || y);
        // console.log(!x);
        // a = 0;
        // b = 5;
        // console.log(a && b);
        // console.log(a || b);
        /*
        条件运算符
        */
        console.log(a>b?a+b:a-b);
    </script>
</head>
<body>

</body>
</html>

test06.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //使用Math对象进行数学运算,用法:Math.方法名(参数)
        //1.绝对值
        console.log(Math.abs(-5));
        //2.计算次方
        console.log(Math.pow(2,4));
        //3.四舍五入
        console.log(Math.round(123.456));
        //4.向上取整,向下取整
        console.log(Math.ceil(3.5));//获取大于等于参数的最小整数
        console.log(Math.floor(3.5));//获取小于等于参数的最大整数
        //5.生成一个[0.0,1)之间的随机浮点数
        console.log(Math.random());
        //6.最大值,最小值
        console.log(Math.max(23,1,54,2,-6));
        console.log(Math.max(23,1,54,2,-6));
        //7.圆周率的值
        console.log(Math.PI)
    </script>
</head>
<body>

</body>
</html>

test07.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var age=25;
        if(age>=60){
            console.log('老年');
        }else if(age>=30){
            console.log('中年');
        }else if(age>=16){
            console.log('少年');
        }else{
            console.log('童年');
        }
        var day="星期五";
        switch(day){
            case '星期一':
                console.log('吃包子!');
                break;
            case '星期二':
                console.log('吃油条!');
                break;
            case '星期三':
            case '星期四':
                console.log('吃面条!');
                break;
            case '星期五':
                console.log('吃油饼!');
                break;
            default:
                console.log('今天不吃了!');
                break;
        }
    </script>
</head>
<body>

</body>
</html>

test08.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //while
        var i = 1;
        var sum = 0;
        while(i<=100)
        {
            if(i%7!=0)
                sum+=i;
            i++;
        }
        console.log(sum);
        //do...while
        var i = 1;
        var sum=0;
        do{
            if(i%7!=0)
                sum+=i;
            i++;
        }while(i<=100);
        console.log(sum);
        /*
        for
        */
        var sum =0 ;
        for(var i =1;i<=100;i++)
            if(i%7!=0)
                sum+=i;
        console.log(sum);
        /*
        for...in...对集合进行遍历
        */
        var str="welcome";//可以将字符串看作是由多个字符组成的集合
        for(var s in str)
        {
// console.log(s);//输出索引
            console.log(str[s]);
        }
    </script>
</head>
<body>

</body>
</html>

test09.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // var arr = new Array();
        // arr[0] = 12;
        // arr[1] = 9;
        // //....可以放任意多个
        // console.log(arr.length);
        // console.log(arr[0]);
        // console.log(arr[4]);
        // var arr = new Array('tom','jack','alice');
        // console.log(arr[arr.length-1]);
        // console.log(arr);
        // var arr = ['tom','jack','alice','mike'];
        // console.log(arr[arr.length-1]);
        // console.log(arr);
        //将1到100之间所有能被3整除的数字,放到数组nums中,输出数组,并统计个数
        // var nums = [];
        // var index = 0;
        // for(var i = 1;i<=100;i++)
        // {
        // if(i%3==0)
        // {
        // // nums[index] = i
        // // index++;
        // //方式2,由于length是动态变化的,所以写length也可以
        // nums[nums.length] = i;
        // //每当向数组中添加元素时:length属性值都会改变
        // }
        // }
        // console.log(nums);
        // var arr = ['tom','jack','alice','mike','admin'];
        // console.log(arr);
        // arr.sort();
        // console.log(arr);
        // var arr = [21,4,34,1,43,23,15,146];
        // console.log(arr);//需要传入一个函数,后面再讲
        // arr.sort();
        // console.log(arr);
        var arr = ['tom','jack','alice','mike','admin'];
        console.log(arr);
        arr.reverse();
        console.log(arr);
        console.log(arr.join())
        console.log(arr.join('-'))
        console.log(arr.indexOf('jack'));
        console.log(arr.lastIndexOf('admin'));
        console.log(arr.slice(1,4)); //包含左边不包含右边
        console.log(arr.slice(1)); //包含左边不包含右边
        console.log(arr.toString());
    </script>
        </head>
<body>

</body>
</html>

test10.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // var arr = new Array();
        // arr[0] = new Array();
        // arr[1] = new Array();
        // arr[0][0] = 12;
        // arr[0][1] = 9;
        // arr[1][0] = 10;
        var arr = [
            [12,54,2,67],
            [1,32,12,5],
            [6,34,7,23]
        ];
        console.log(arr[0][1]);
        for(var i = 0;i<arr.length;i++)
        {
            for (var j = 0; j < arr[i].length; j++)
                document.write(arr[i][j]+'&nbsp;&nbsp;');
            document.write('<br>');
        }
    </script>
</head>
<body>

</body>
</html>

test11.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        自定义函数
        */
        //1.定义函数
        function show()
        {
            console.log('嘿嘿');
        }
        function calc(num1,num2,num3)
        {
            console.log(num1,num2,num3);
            var sum = num1+num2+num3;
            console.log(sum);
            // return sum;//返回值
        }
        //2.调用函数
        show();
        var result = calc(12,6,2);//calc(12,6,2,7),calc(12,6)看一下仍然可以正常使用
        console.log(result);
        //3.变量的作用域
        var c = 6;//全局变量
        // function fn()
        // {
        // var a = 5;//局部变量
        // console.log(a);
        // console.log(c);
        // }
        var fn()
        {
            if(true)
            {
                var a = 5;//局部变量
                let a = 5;//块级变量
                console.log(a);
            }
            console.log(a);
        }
        {
            var d = 2;//全局变量
            let x = 4;
            console.log(x);
        }
        // console.log(a);
        console.log(c);
        // var b;
        // console.log(b);
    </script>
</head>
<body>

</body>
</html>

test12.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function f1()
        {
            console.log('111');
        }
        // f1();//立即执行
        //当单击窗口时就执行f1
        // window.οnclick=f1();//常规做法,在console窗口显示,有问题,加小括号立即就执行了
        // window.οnclick=f1;//回调执行,即回头调用此函数,不能加括号
        /*
        函数本身也是一种数据类型
        数据类型:string、number、boolean、null、undefined、object、
        function
        */
        // console.log(typeof f1);//这是一个function
        // var a = f1;
        // console.log(typeof a);
        //将一个函数f1作为另一个函数f2的参数
        function f2(x,y)
        {
// console.log(x);
// console.log(y);
//上述功能打印输出f1函数
            y();//这样就可以调用f1了
        }
        // f2(5,f1);//f1是一个函数,作为实参 f1没有执行,只是打印输出
        /*
        示例
        */
        var arr = [12,4,23,6,26,86];
        /*
        定义一个比较器
        升序:如果第一个参数比第二个参数大,则返回正数
        如果第一个参数比第二个参数小,则返回负数
        如果两个参数相等,则返回0
        */
        function compareFn(a,b)
        {
            return a-b;
            //降序 b-a
            // if(a>b)
            // return 1;
            // else if(a<b)
            // return -1;
            // else
            // return 0;
        }
        arr.sort(compareFn);//将自定义比较规则函数作为函数参数传入
        console.log(arr);
        function show(value,index)
        {
            console.log(index,value);
        }
        arr.forEach(show);//这也是数组本身提供的一个方法
    </script>
</head>
<body>

</body>
</html>

test13.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        1.一般用于回调
        */
        // function show()
        // {
        // console.log('111');
        // }
        // window.οnclick=show;
        window.onclick=function()//匿名函数,一般用于回调
        {
            console.log('111');
        };
        // function f1()
        // {
        // console.log('2222');
        // }
        // var a = f1;//如果单纯要把f1赋值给a,就没有必要再起名字为f1了
        var a = function ()
        {
            console.log('2222');
        };
        var arr = [12,4,23,6,2,86];
        function show(value,index)
        {
            console.log(index,value);
        }
        // arr.forEach(show);
        //这是回调
        arr.forEach(function(value,index)
        {
            console.log(index);
            console.log(value);
        });
        // function (){
        //
        // }这是错误的
        /*
        2.自执行函数
        */
        function fn() {
            console.log(3333);
        }
        // fn();//这个函数假如只执行一次,不必要起名字
        (
            function () {
                console.log(333);
            }
        )();
    </script>
</head>
<body>

</body>
</html>

test14.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        箭头函数:语法:
        参数 => 返回值
        */
        // var a = function (x) {
        // return x*2;
        // }//匿名函数
        // var a = x => x*2;//优点:更简洁
        //示例2 如果箭头函数没有参数或有2个以上参数,则必须使用小括号表示参数部分
        var a =function (x,y) {
            return 5;
        }
        // var a = =>5;//这是错误的
        // var a = (x,y)=>5;
        //示例3:如果箭头函数的函数体多于一条语句,则必须使用大括号将它们括起来
        // var a = function (x,y) {
        // var sum=x+y;
        // return sum;
        // }
        var a = (x,y) =>{
            var sum = x+y;
            return sum;
        }
        // var a = function (x) {
        // console.log(x);
        // }
        var a = x=> console.log(x);//这样写没作用
        // a(5);
        // console.log(a(5)); 这样写不太合适
        //应用场景
        var arr = [12,4,23,6,2,86];
        arr.forEach((value,index)=>{
            console.log(index,value*2);
        });
        window.onclick= ()=>{
            console.log(111);
        };
    </script>
</head>
<body>

</body>
</html>

test15.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // var str = 'hello world';
        var str = 'hello world welcome to nanjing';
        console.log(str.length);
        console.log(str.charAt(0),str.charAt(3),str[0],str[str.length-1]);
        console.log(str.replace('el','xxxx'));
        console.log(str.indexOf('o'));
        console.log(str.lastIndexOf('o'));
        console.log(str.toLowerCase());
        console.log(str.toUpperCase());
        console.log(str.substring(1,4));
        console.log(str.split(' '));//将str改为hello world welcome tonanjing
        console.log(str.split(' ',3))
        console.log(str.trim());//去掉前后空格
        var s = new String('hello');
        console.log(str);
        console.log(s);
        console.log(s.toUpperCase());
    </script>
</head>
<body>

</body>
</html>

test16.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var date = new Date();
        // var date = new Date(2020,2,14,12,30,25);//月份的取值范围[0,11]
        // var date = new Date(1234432121);
        console.log(date);
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        var d = date.getDate();
        var hour = date.getHours();
        var miniute = date.getMinutes();
        var second = date.getSeconds();
        let milliseconds = date.getMilliseconds();
        let day = date.getDay();
        var weekday = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
            let time = date.getTime();
        console.log(time);
        console.log(day);
        var currentTime = year + '年'+checkDate(month)+'月'+checkDate(d)+'日 '+ checkDate(hour) +':'+checkDate(miniute)+':'+checkDate(second) +weekday[day];document.write(currentTime);
        function checkDate(num)
        {
            if(num<10)
                return '0'+num;
            else
                return num;
        }
    </script>
</head>
<body>

</body>
</html>

test17.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //定义一个JSON对象
        var user={
            "id":1001,
            "name":"tom",
            "age":20,
            "height":180.5,
// "address":"山西太原",
            "address":{
                "province":"山西",
                "city":"太原市",
                "district":"小店区"
            },
            "isMarried":true
        };
        //访问方式:对象名.属性名
        // console.log(user.name);
        // console.log(user.height);
        // console.log(user.address);
        // console.log(user.address.city);
        //JSON对象数组
        // var nums = [12,3,42,43];
        var users=[
            {"id":9527,"username":"admin","password":"123","status":1},
            {"id":9528,"username":"tom","password":"111","status":1},
            {"id":9529,"username":"jack","password":"222","status":0},
            {"id":9530,"username":"alice","password":"333","status":1}
        ];//一般要换行写,可读性更高
        for(var i=0;i<users.length;i++){
            var u =users[i];
        // console.log(u.id,u.username,u.password,u.status);
        }
        /*
        JSON对象和字符串之间的转换
        */
        //1.将JSON对象转换为字符串
        // console.log(typeof user)
        // console.log(user);
        //
        // var str = JSON.stringify(user);
        // console.log(typeof str);
        // console.log(str);
        //2.将字符串转换为JSON对象
        // var str ="{'name':'zhangsan','age':18,'sex':'男'}";//报错了
        var str ='{"name":"zhangsan","age":18,"sex":"男"}';//JSON语法规定
        var obj = JSON.parse(str);
        console.log(typeof obj);//报错了,改双引号就正常了
        console.log(obj.age);
    </script>
</head>
<body>

</body>
</html>

test18.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        1.使用object
        */
        var stu = new Object();
        //添加属性
        stu.name = 'tom';
        stu.age = 18;
        stu.height = 180.5;
        //添加方法
        stu.study=function () {
            console.log('我叫'+stu.name+',正在学习....');
        };
        stu.run=function () {
            console.log('正在参加马拉松....');
        };
        //调用属性
        // console.log(stu.name,stu['age']);
        // stu.study();
        // stu.run();
        /*
        2.使用构造函数
        */
        // var date = new Date(2020,5,13);//和这个类似
        function Student(name,age,sex) {
// console.log(name,age,sex);//这是就是个函数
//属性
            this.name = name;
            this.age = age;
            this.sex = sex;
//方法
            this.show=function () {
                console.log('我叫'+this.name+',年龄:'+this.age+',性别:'+this.sex);
            };
            this.study()=function () {
                console.log('正在学习......');
            };
        }
        // Student('tom',20,'male');调用函数
        // var student = new Student('tom',20,'male');
        // console.log(Student.name,Student.age);
        // student.show();
        // student.study();
        /*
        3.使用JSON对象
        */
        var student = {
            "name":"tome",
            "age":18,
            "sex":"male",
            "study":function () {
                console.log('正在学习....');
            }
        };
        console.log(student.name,student['age']);
        student.study();
    </script>
</head>
<body>

</body>
</html>

test19.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function query() {
        // console.log(1111);
        /*
        1.根据id获取,返回单个值
        */
        // var objDiv = document.getElementById('mydiv');
        // console.log(typeof objDiv);//Dom对象
        // console.log(objDiv);
        /*
        2.根据name获取,返回集合 也就是数组
        */
        // var objs = document.getElementsByName('hobby');
        // // console.log(objs);
        // for(var index in objs)
        // console.log(objs[index]);
        /*
        3.根据标签名获取,返回集合
        */
        // var objs = document.getElementsByTagName('input');
        // for(var index in objs)
        // console.log(objs[index]);
        /*
        4.根据CSS选择器来获取单个对象
        */
        // var obj = document.querySelector('#div2');//id选择器
        // var obj = document.querySelector('.aaa');//类选择器
        // var obj = document.querySelector('p.aaa');//嵌套选择器
        // console.log(obj);
        /*
        5.根据CSS选择器来获取多个对象
        */
        // var objs = document.querySelectorAll('.aaa');
        // // console.log(objs.length);
        // console.log(objs);
        /*
        根据已有节点来获取其他节点
        */
            var obj = document.getElementById('second');
// console.log(obj);
// console.log(obj.parentNode);//父节点
            console.log(obj.previousSibling);
            console.log(obj.previousSibling.previousSibling);
            console.log(obj.nextSibling);
            console.log(obj.parentNode.firstChild);
            console.log(obj.parentNode.lastChild);
        }
    </script>
</head>
<body>
    <input type="button" value="获取页面中的元素" onclick="query()">
    <div id="mydiv" class="aaa">hello</div>
    <!--<div id="mydiv">world</div>只能获取到第1个-->
    <div id="div2" class="aaa">world</div>
    <p class="aaa">welcome</p>
    爱好: <input type="checkbox" value="eat" name="hobby"> 吃饭
        <input type="checkbox" value="sleep" name="hobby"> 睡觉
        <input type="checkbox" value="doudou" name="hobby"> 打豆豆
    姓名:<input type="text" name="username">
    <!--ul>li*4-->
    <ul>aaa
        <!--<li>tom</li>-->
        <!--<li id = "second">jack</li>-->
        <!--<li>mike</li>-->
        <!--<li>alice</li>-->
        <li>tom</li>bbb
        <li id = "second">jack</li><li>mike</li><li>alice</li>cccc
    </ul>
</body>
</html>

test20.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hello{
            width: 300px;
            height: 300px;
            background: green;
            font-size: 40px;
        }
        .world{
            text-decoration: underline;
            font-weight: blod;
        }
    </style>
    <script>
        function getProperty(){
            //1.获取属性的值
            // let obj = document.getElementById("baidu");
            // console.log(obj.href);
            // console.log(obj.target);
            // let obj = document.getElementById("male");
            // console.log(obj.value);
            // let obj =document.getElementById("male");
            // console.log(obj.checked);//返回值true或false
            //设置属性的值
            // let obj = document.getElementById("baidu");
            // obj.href="http://www.sxgjpx.net";
            // obj.target="_self";
            // let obj = document.getElementById("female");
            // obj.checked=true;
        }
        //获取内容
        function getContent() {
            let obj = document.getElementById("mydiv");
            //获取内容
            // console.log(obj.innerHTML);
            console.log(obj.innerText);
            //设置内容
            // obj.innerHTML="<h2>世界你好</h2>";
            // obj.innerText="<h2>你好世界</h2>";
        }
        //访问CSS
        function getStyle() {
            var obj = document.getElementById("mydiv");
            // console.log(obj.style);
            // console.log(obj.style.width);
            // console.log(obj.style.height);
            // console.log(obj.style.background);
            // console.log(obj.style.borderTopRightRadius);

            //设置CSS样式属性
            // obj.style.width="300px";
            // obj.style.background="blue";
            // obj.style.fontSize="20px";

            //设置类选择器
            obj.className="world";
            console.log(obj.className);
        }
    </script>
</head>
<body>
    <input type="button" value="获取属性" onclick="getProperty()">
    <input type="button" value="访问内容" onclick="getContent()">
    <input type="button" value="访问CSS" onclick="getStyle()">
    <hr>
    <!--<a href="https://www.baidu.com" target="_blank" id="baidu">百度</a>
    <br>-->
    <a href="https://www.baidu.com" target="_blank" id="baidu">点我</a><br>
    用户名:<input type="text" value="" name="username" id="username"> <br>
    性别:<input type="radio" name="sex" value="male" id="male"><input type="radio" name="sex" value="female" id="female"><br>
    <div id="mydiv">
        hello world
    </div>
</body>
</html>

test21.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>

    </style>
    <script>
        function change() {
            if($("baidu").checked){
                $("logo").src="images/baidu.png";
                $("frmSearch").action="https://www.baidu.com/s";
                $("txtSearch").name="wd";
                $("btnSearch").value="百度搜索";
            }
            else if($("sogou").checked){
                $("logo").src="images/sogou.png";
                $("frmSearch").action="https://www.sogou.com/web";
                $("txtSearch").name="query";
                $("btnSearch").value="搜狗搜索";
            }
            else{
                $("logo").src="images/360.png";
                $("frmSearch").action="https://www.so.com/s";
                $("txtSearch").name="q";
                $("btnSearch").value="360搜索";
            }
        }
        function $(id) {
            return document.getElementById(id);
        }
    </script>
</head>
<body>
<input type="radio" name="search" id="baidu" checkedonclick="change()"><label for="baidu">百度</label>
<input type="radio" name="search" id="sogou" onclick="change()"><label
        for="sogou">搜狗</label>
<input type="radio" name="search" id="360" onclick="change()"><label
        for="baidu">360</label>
<form action="https://www.baidu.com/s" id="frmSearch">
    <img src="images/baidu.png" id="logo">
    <input type="text" name="wd" id="txtSearch" placeholder="请输入要查
询关键词">
    <input type="submit" id="btnSearch" value="百度搜索">
</form>
</body>
</html>

test22.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function doAdd() {
            //创建一个li
            //1.创建元素节点
            var li = document.createElement("li");
            //2.设置文本内容
            // var txt = document.createTextNode('alice');
            // li.appendChild(txt);
            li.innerText="alice";//设置文本
            // console.log(li);
            //3.设置属性
            // li.id="fourth";
            li.setAttribute("id","fourth");//设置属性
            // console.log(li.getAttribute("id"));//获取属尾
            // console.log(li.id);
            //4.将li放到ul的末尾,添加到节点中
            var ul = document.getElementById("myul");
            // ul.appendChild(li);
            //5.将alice添加到jack的前面
            // ul.insertBefore(li,document.getElementById("second"));
            //6.替换节点 用alice替换jack
            ul.replaceChild(li,document.getElementById("second"));
        }
        function doDelete() {
            //删除当前节点
            // document.getElementById("first").remove();
            var ul = document.getElementById("myul");
            // ul.removeChild(document.getElementById("first"));
            ul.removeChild(ul.lastChild);
        }
    </script>
</head>
<body>
<input type="button" value="添加" onclick="doAdd()">
<input type="button" value="删除" onclick="doDelete()">
<ul id="myul">
    <li id="first">tom</li>
    <li id="second">jack</li>
    <li>mike</li>
</ul>
</body>
</html>

test23.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function f1() {
            console.log(111);
        }
        window.onload = function (){
            // var btn2 = document.getElementById("btn2");//由于代码执行到此时,该部分代码会优于页面加载而先执行
            // console.log(btn2);
            // btn2.οnclick=function (){
            // console.log(222);
            // };
            document.getElementById("btn2").onclick=function (event){
                console.log(222);
                console.log(event);
                console.log(event.srcElement);
                console.log(this);//this等价于event.srcElement 表示事件源
            };
            // document.getElementById("btn2").οnclick=f1;
            var hobbies = document.getElementsByName("hobby");
            // console.log(hobbies);
            for(var i =0;i<hobbies.length;i++)
            {
                // console.log(hobbies[i]);
                console.log(i);
                hobbies[i].onclick=function (){
                    // console.log(hobbies[i].value);
                    // console.log(i);
                    console.log(this.value);
                };//onclick事件没有触发前 循环先执行 i 0-3
            }
        };
    </script>
</head>
<body>
    <!--方式一:静态绑定-->
    <!--<input type="button" value="按钮1" οnclick="alert('哈哈')">-->
    <input type="button" value="按钮1" onclick="f1()">
    <!--方式二:动态绑定-->
    <input type="button" value="按钮2" id="btn2">
    爱好: <input type="checkbox" name="hobby" value="eat">吃饭
            <input type="checkbox" name="hobby" value="sleep">睡觉
            <input type="checkbox" name="hobby" value="doudou">打豆豆
</body>
</html>

test24.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #container{
            text-align: center;
        }
        #mytable{
            width: 500px;
            text-align: center;
            border:1px solid #ccc;
            margin:0 auto;//左右居中
        }
        #mytable td,#mytable th{
            border:1px solid #ccc;
        }
        #mytable tfoot tr{
            text-align: right;
        }
        tfoot tr td:first-child{
            text-align: center;
        }
    </style>
    <script>
        window.onload=function(){
            //为添加按扭绑定事件
            $("btnAdd").onclick=function(){
                //创建tr
                var tr = document.createElement("tr");
                //创建td
                tdChk = document.createElement("td");
                var tdName =document.createElement("td");
                var tdAge =document.createElement("td");
                var tdSex =document.createElement("td");
                var tdPhone =document.createElement("td");
                var tdDelete = document.createElement("td");

                //将数据添加到td中
                var chkDelete = document.createElement("input");
                chkDelete.type="checkbox";
                chkDelete.className="chk";
                tdChk.appendChild(chkDelete);
                chkDelete.onclick=function (){
                    var chks = document.querySelectorAll(".chk");
                     //统计已选中的数量
                    var cnt =0;
                    for(var j =0;j<chks.length;j++){
                        if(chks[j].checked) {
                            cnt++;
                        }
                    }
                    //判断是否全部选中
                    if(cnt==chks.length){
                        $("all").checked=true;
                    }
                    else{
                        $("all").checked=false;
                    }
                };
                tdName.innerText=$("name").value;
                tdAge.innerText=$("age").value;
                tdSex.innerText=$("m").checked?$("m").value:$("f").value;
                tdPhone.innerText=$("phone").value;
                //创建input按钮
                var btnDelete = document.createElement("input");
                btnDelete.type="button";
                btnDelete.value="删除";
                btnDelete.onclick=function () {
                    this.parentNode.parentNode.remove();
                };
                tdDelete.appendChild(btnDelete);

                //将td添加tr中
                tr.appendChild(tdChk);
                tr.appendChild(tdName);
                tr.appendChild(tdAge);
                tr.appendChild(tdSex);
                tr.appendChild(tdPhone);
                tr.appendChild(tdDelete);

                //将tr添加到tbody
                $("tb").appendChild(tr);
            };
            //为删除按钮绑定事件
            var btnDeletes = document.querySelectorAll(".delete");
            for(var i =0;i<btnDeletes.length;i++){
                btnDeletes[i].onclick=function(){
                    this.parentNode.parentNode.remove();
                };
            }
            //为首行删除绑定事件
            $("btnDeleteFirst").onclick=function(){
                $("tb").getElementsByTagName("tr")[0].remove();
            };
            //为末行删除绑定事件
            $("btnDeleteLast").onclick=function(){
                var trs = $('tb').getElementsByTagName("tr");
                trs[trs.length-1].remove();
            };
            //为全选绑定事件
            $("all").onclick=function(){
                if($("all").checked)
                {
                    var chks = document.querySelectorAll(".chk");
                    for (var i = 0; i < chks.length; i++) {
                        chks[i].checked = true;
                    }
                }
                else{

                }
                var chks = document.querySelectorAll(".chk");
                for(var i =0 ;i<chks.length;i++){
                    chks[i].checked=false;
                }
            }
        };
        //实现当选中下面所有的复选框时全选
        var chks = document.querySelectorAll(".chk");
        for(var i =0;i<chks.length;i++){
            chks[i].onclick=function(){
                // console.log(111);
                //统计已选中的数量
                var cnt =0;
                for(var j =0;j<chks.length;j++){
                    if(chks[j].checked) {
                        cnt++;
                    }
                }
                //判断是否全部选中
                if(cnt==chks.length){
                    $("all").checked=true;
                }
                else{
                    $("all").checked=false;
                }
            };
        }
        //为删除多个按钮绑定事件
        $("btnDeleteMulti").onclick=function (){
            var chks = document.querySelectorAll(".chk");
            for(var i =0 ;i <chks.length;i++)
            {
                if(chks[i].checked){
                    chks[i].parentNode.parentNode.remove();
                }
            }
        };
        function $(id){
            return document.getElementById(id);
        }
    </script>
</head>
<body>
<div id="container">
    <table id="mytable">
        <thead>
        <tr>
            <th>
                全选 <input type="checkbox" id="all">
            </th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>电话</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="tb">
        <tr>
            <td><input type="checkbox" class="chk"></td>
            <td>tom</td>
            <td>20</td>
            <td>male</td>
            <td>110</td>
            <td><input type="button" value="删除" class="delete"></td>
        </tr>
        <tr>
            <td><input type="checkbox" class="chk"></td>
            <td>jack</td>
            <td>22</td>
            <td>male</td>
            <td>119</td>
            <td><input type="button" value="删除" class="delete"></td>
        </tr>
        <tr>
            <td><input type="checkbox" class="chk"></td>
            <td>alice</td>
            <td>20</td>
            <td>female</td>
            <td>120</td>
            <td><input type="button" value="删除" class="delete"></td>
        </tr>
        </tbody>
        <tfoot>
        <tr>
            <td><input type="button" value="删除多个"
                       id="btnDeleteMulti"></td>
            <td colspan="5">
                <input type="button" value="从首行删除"
                       id="btnDeleteFirst">
                <input type="button" value="从末行删除"
                       id="btnDeleteLast">
            </td>
        </tr>
        </tfoot>
    </table>
    <form action="" id="myform">
        姓名: <input type="text" id="name"> <br>
        年龄: <input type="text" id="age"> <br>
        性别:<input type="radio" name="sex" id="m" value="male"
                  checked><input type="radio" name="sex" id="f" value="female"><br>
        电话:<input type="text" id="phone"> <br>
        <hr>
        <input type="button" value="添 加" id="btnAdd">
        <input type="reset" value="重 置">
    </form>
</div>
</body>
</html>

test25.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #username{
            outline: none;
        }
        .txtborder{
            border:1px solid red;
        }
        #img{
            width: 160px;
            height: 160px;
        }
        </style>
          <script>
          window.onload=function () {
        /*
        鼠标事件
        */
        // document.getElementById("btn").οnclick=function(){
        // document.getElementById("btn").οndblclick=function(){
        // document.getElementById("btn").οnmοuseοver=function(){
        // document.getElementById("btn").οnmοusedοwn=function(){
        // console.log(111);
        // };
        // document.getElementById("btn").οnmοuseοut=function(){
        // document.getElementById("btn").οnmοuseup=function(){
        // document.getElementById("btn").οnmοusemοve=function(){
        // console.log(222);
        // };
        /*
        键盘事件
        */
        // document.getElementById("username").οnkeydοwn=function(){
        // console.log(111);
        // };
        // document.getElementById("username").οnkeyup=function(){
        // console.log(222);
        // };
        //
        document.getElementById("username").onkeypress=function(event){
        // // console.log(222);
        // console.log(event);
        // };
        /*
        表单事件
        */
        // document.getElementById("username").οnfοcus=function(){
        // console.log(111);
        //
        document.getElementById("username").className="txtborder";
        // }
        // document.getElementById("username").οnblur=function(){
        // console.log(222);
        // document.getElementById("username").className="";
        // };
        document.getElementById("username").onselect=function(){
            console.log(222);
        // document.getElementById("username").className="";
        };
        // document.getElementById("head").οnchange=function(event){
        // console.log(222);
        // console.log(event);
        //
        document.getElementById("img").src=window.URL.createObjectURL(this.files[0]
        );
        // };
        document.getElementById("frm").onsubmit=function(){
            console.log(111);
        // return false;//阻止表单提交
        return true;
        };
        };
        </script>
</head>
<body>
<form action="" id="frm">
<input type="button" value="点 我" id="btn"> <br>
用户名:<input type="text" id="username" name="username"> <br>
<img src="" id="img"> <br>
头像:<input type="file" id="head" multiple> <br>
<input type="submit" value="提交">
</form>
</body>
</html>

test26.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            background: pink;
        }
        p{
            width: 100px;
            height: 100px;
            background:#ccc;
        }
    </style>
    <script>
        function f1(event) {
// console.log(event);
// event.stopPropagation();//阻止事件冒泡,W3C标准方式
// event.cancelBubble=true;
// alert(111);
        }
        window.onload=function(){
//绑定鼠标右键点击事件
            document.getElementById("btn").oncontextmenu=function(){
                event.preventDefault();//阻止默认行为
                this.style.color="red";
            };
            document.getElementById("mya").onclick=function (event) {
                event.preventDefault();//阻止事件默认行为
                this.innerHTML="新浪";
            };
        };
    </script>
</head>
<body>
    <div onclick="alert(333)">
        <p onclick="alert(222)">
            <!--<input type="button" value="点我" οnclick="alert(111)">-->
            <input type="button" value="点我" onclick="f1(event)" id="btn">
        </p>
    </div>
    <a href="https://www.baidu.com" id="mya" target="_blank">百度</a>
    <a href="#" id="mya" target="_blank">百度</a>
</body>
</html>

test27.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function getDegree() {
            var degree =document.getElementById("degree")
// console.log(degree.length);
// console.log(degree.selectedIndex);
            var opts = degree.options;
// console.log(opts);
// var opt = opts[degree.selectedIndex]
// console.log(opt);
// console.log(opt.text,opt.value);
// opts[1].text="中专";
// opts[1].value="zhongzhuan";
//当修改了opts数组中的内容时,下拉列表中的值也会改变
// console.log(opts[opts.length]);//由于是一个undefined所以会报// opts[opts.length].text="博士";//报错,为什么?
        // opts[opts.length].value="boshi";
            //前面学过的方法
// var option = document.createElement("option");
// option.innerText="博士";
// option.value="boshi";
// degree.appendChild(option);
//新知识1,更简单
// opts[opts.length]=new Option("博士","boshi");//实际上还是操作
            数组
//新知识2
// var option=new Option("博士","boshi");
// degree.add(option);
            var option = new Option("中专","zhongzhuan");
            degree.add(option,degree.getElementsByTagName("option")[1]);
        }
        window.onload=function(){
            document.getElementById("degree").onchange=function(){
// console.log(111);
// console.log(this.options[this.selectedIndex].value);
                console.log(this.value);
            };
        };
    </script>
</head>
<body>
<input type="button" value="操作下拉列表" onclick="getDegree()">
<hr>
学历:
<select id="degree">
    <option value="0">---请选择学历---</option>
    <option value="gaozhong">高中</option>
    <option value="dazhuan">大专</option>
    <option value="benke">本科</option>
    <option value="yanjiusheng">研究生</option>
</select>
</body>
</html>

test28.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var provinces = [
            {
                id:1001,
                name:"山西省",
                cities:[
                    {
                        id:1,
                        name:"太原市"
                    },
                    {
                        id:2,
                        name:"大同市"
                    },
                    {
                        id:3,
                        name:"长治市"
                    },
                    {
                        id:4,
                        name:"忻州市"
                    },
                    {
                        id:5,
                        name:"吕梁市"
                    }
                ]
            }
        ];
        window.onload=function(){
//初始化省份
            for(var i in provinces){
                var p =provinces[i];
                var option = new Option(p.name,p.id);
                document.getElementById("province").add(option);
            }
        };
        function change() {
//清空城市数据
            document.getElementById("city").length=0;
//获取选择的省份
            var pid = document.getElementById("province").value;
            if(pid==0){
                document.getElementById("city").add(new Option("--请选择城
                市--"));
                return ;
            }
            for (var i in provinces){
                var p = provinces[i];
                if (p.id == pid) {
//添加城市
                    var cities = p.cities;
                    for (var j in cities) {
                        var option = new Option(cities[j].name,
                            cities[j].id);
                        document.getElementById("city").add(option);
                    }
                    return;
                }
            }
        }
    </script>
</head>
<body>
    <!--注意:name可以不用,因为不用提交-->
    省份:
    <select id="province" onchange="change()">
        <option value="0">--请选择省份--</option>
    </select>
    城市:
    <select id="city">
        <option value="0">--请选择城市--</option>
    </select>
</body>
</html>

test29.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //doment.getElementById()
        //window.history
        //window.location
        /*
            window常用方法
        */
        // 1.alert();
        // window.alert(111);
        // alert(111);

        //  2.prompt()
        // var name = window.prompt("请输入用户名","无名氏");
        // console.log(name);

        // 3.confirm()
        // var flag = confirm("确定要删除码?");
        // console.log(flag);

        // 4.open()
        function f1() {
            open("test28.html","test28","width=200px,height=200px,resizable=no");
        }

        // 5.setTimeout()
        var timer_one;
        var timer_zq;
        function f2() {
            timer_one = setTimeout(function(){
                console.log(111);
            },3000);//单位毫秒
        }
        // function show() {
        //     console.log(111);
        // }

        // 6.setInterval()
        function f3() {
            timer_zq = setInterval(function () {
                console.log("起床啦!!!");
            },1000)
        }

        // 周期性计时器使用一次性计时器能否实现
        // function f2() {
        //     setTimeout(show,1000);//单位毫秒
        // }
        // function show() {
        //     console.log(111);
        //     setTimeout(show,1000);
        // }

        // 7.clearTimeout()
        function f4() {
            clearTimeout(timer_one);
        }

        // 8.clearInterval()
        function f5() {
            clearInterval(timer_zq);
        }

        /*
            window常用事件
        */
        // window.onload
        window.onscroll=function(){
            console.log(222);
        }

        window.onclick=function(){
            console.log(333);
        }

        window.onload=function(){
            console.log(444);
        }

        // 一个对象可以绑定多个事件,但一个事件不能被绑定多次
        window.onload=function(){
            console.log(555);
        }
    </script>
</head>
<body>
    <input type="button" value="打开一个新窗口" onclick="f1()"><br>
    <input type="button" value="一次性计时器" onclick="f2()"><br>
    <input type="button" value="周期性计时器" onclick="f3()"><br>
    <input type="button" value="关闭一次性计时器" onclick="f4()"><br>
    <input type="button" value="关闭周期性计时器" onclick="f5()"><br>
    <hr>
    <p style="background: #ccc;height: 2000px">
        Hello world!
    </p>
</body>
</html>

test30.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function f1() {
            // console.log(location.href);//获取location的href属性
            location.href="https://www.baidu.com";
            location.reload();
        }

        function f2() {
            history.back();
        }

        function f3() {
            history.forward();
        }
    </script>
</head>
<body>
    <input type="button" value="操作location" onclick="f1()"><br>
    <input type="button" value="后退" onclick="f2()"><br>
    <input type="button" value="前进" onclick="f3()"><br>
</body>
</html>

test31.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var timer;
        var l=0,r=0;//全局变量可以保留上一次调用结束时的值
        function doStart() {
            $("start").disabled=true;
            $("stop").disabled=false;
            timer = setInterval(function () {
                r++;
                if(r>9){
                    r=0;
                    l++;
                }
                if(l>9){
                    r=0;
                    l=0;
                }
                $("imgr").src="images/number/"+r+".bmp";
                $("img1").src="images/number/"+l+".bmp";
            },500)
        }

        function doStop() {
            $("stop").disabled=true;
            $("start").disabled=false;
            clearInterval(timer);
        }
        function $(id) {
            return document.getElementById(id);
        }
    </script>
</head>
<body>
<table>
    <tr>
        <td><img src="images/number/0.bmp " id="imgl"></td>
        <td><img src="images/number/0.bmp " id="imgr"></td>
    </tr>
    <tr>
        <td><input type="button" value="开始" id="start" onclick="doStart()"></td>
        <td><input type="button" value="停止" id="stop" onclick="doStop()" disabled></td>
    </tr>
</table>
</body>
</html>

test32.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //方式1:定义正则表达式对象
        // var reg = /a/i;
        // console.log(reg.test('heAllo'));

        //方式2:定义正则表达式对象
        // var reg = new RegExp('a','i');
        // console.log(reg.test('helloA'));

        //规则验证:
        // var reg = /a\s/;//a字符后是否包含空白字符
        // console.log(reg.test('hea llo'));
        //
        // var reg = /a\s\d/i;//是否包含数字字符
        // console.log(reg.test('hea 8llo'));

        // var reg = /a\s\d\w/i;//匹配任何字符 数字、字母、下划线
        // console.log(reg.test('hela 8lo'));

        // 量词
        // var reg = /a\s\d{3}\w/i;//连续出现3个数字
        // console.log(reg.test('hela 653_lo'));
        // var reg = /a\s\d{0,3}\w/i;
        // console.log(reg.test('hela 2k2o5j12221_lo'));
        // var reg = /\d?/i;
        // console.log(reg.test('hela 2k2o5j12221_lo'));
        //特殊符号
        // var reg = /a/; //是否包含a字符
        // console.log(reg.test('heallo'));

        // var reg = /^a/;//是否以a开头 a结尾
        // // var reg = /a$/;//是否以a结尾
        //
        // console.log(reg.test('ahello'));
        // var reg = /\da$/;//以a结尾,且a的前面是个数字
        // console.log(reg.test('heallo3a'));
        //
        // var reg = /^a$/; //是否包含a字符
        // console.log(reg.test('a'));


        // var reg = /^a\da$/;//以a开头,且以a结尾,中间有一个数字
        // console.log(reg.test('a3a'));

        // var reg = /^a\d+a$/;//以a开头,且以a结尾,中间有一个数字,+表示数字可以出现多次
        // console.log(reg.test('a2a'));

        // var reg = /^a\d*a$/;//以a开头,且以a结尾,中间有一个数字,*表示数字可有可无
        // console.log(reg.test('aa'));

        // var reg = /^a\d?a[\dabc]$/; //[0-9 abc]表示从数字、a、b、c中选一个结尾
        // console.log(reg.test('a2aa'));

        // var reg = /^a\d?a[\dabc]{2}$/; //[0-9 abc]表示从数字、a、b、c中选2个结尾
        // console.log(reg.test('a2ac8'));

        // var reg = /^a\d?a[\dabc]{2}(\da){3}$/; //[0-9 abc]表示从数字、a、b、c中选2个结尾,且数字a可以连续出现3次
        // console.log(reg.test('a2ac87a8a9a'));
        // var reg = /^a|b+%/;//b至少出现1次
        // console.log(reg.test('ab'));

        var reg = /^[^abc]{2}/;//只要不是abc开头就行
        console.log(reg.test('dlh'));
    </script>
</head>
<body>

</body>
</html>

test33.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table tr td:first-child{
            text-align: right;
        }
        .error{
            font-size: 12px;
            color: red;
        }
        .ok{
            color: green;
        }
    </style>
    <script>
        function checkUsername(){
            //用户名只能由字母、数字、下划线、横线、中文组成,且只能以数字或字母开头和结尾,长度为6-16位
            var username = $("username").value;
            var reg = /^[\da-z][\u4E00-\u9FA5\w-]{4,12}[\da-z]$/i;
            if(!reg.test(username)){
                $("usernameInfo").innerText="用户名只能由字母、数字、下划线、横线、中文组成,长度为6-16位";
                $("usernameInfo").className="error";
                return false;
            }else{
                $("usernameInfo").innerText="√";
                $("usernameInfo").className="ok";
                return true;
            }
        }
        function checkPassword(){
            //密码只能由数字、字母组成,长度为6-10位
            var password = $("password").value;
            var reg = /^[\da-z]{6,10}$/i;
            if(!reg.test(password)){
                $("passwordInfo").innerText="密码只能由数字、字母组成,长度为6-10位";
                $("passwordInfo").className="error";
                return false;
            }else {
                $("passwordInfo").innerText="√";
                $("passwordInfo").className="ok";
                return true;
            }
        }
        function checkRepassword(){
            //两次输入的密码必须相同
            var password = $("password").value;
            var repassword = $("repassword").value;
            if(password!=repassword){
                $("repasswordInfo").innerText="两次输入的密码不一致,请重新输入";
                $("repasswordInfo").className="error";
                return false;
            }else{
                $("repasswordInfo").innerText="√";
                $("repasswordInfo").className="ok";
                return true;
            }

        }
        function checkBirthday() {
            //出生日期
            var birthday = $("birthday").value;
            var reg = /^\d{4}-\d{1,2}-\d{1,2}/;
            if(!reg.test(birthday)){
                $("birthdayInfo").innerText="请输入正确的日期";
                $("birthdayInfo").className="error";
                return false;
            }else{
                $("birthdayInfo").innerText="√";
                $("birthdayInfo").className="ok";
                return true;
            }
        }
        function checkPhone(){
            var phone = $("phone").value;
            var reg =/^1\d{10}$/;
            if(!reg.test(phone)){
                $("phoneInfo").innerText="请输入正确的电话号码";
                $("phoneInfo").className="error";
                return false;
            }else{
                $("phoneInfo").innerText="√";
                $("phoneInfo").className="ok";
                return true;
            }
        }
        function checkMail(){
            var mail = $("mail").value;
            //tom@sina.com.cn   tom@baidu.com
            var reg = /^\w+@\w+(\.[a-z]{2,3}){1,2}$/;//+表示至少有1个字符 点号不能直接写要转义\.
            if(!reg.test(mail)){
                $("mailInfo").innerText="请输入正确的邮箱";
                $("mailInfo").className="error";
                return false;
            }else{
                $("mailInfo").innerText="√";
                $("mailInfo").className="ok";
                return true;
            }

            //身份证
            // var reg = /^[1-9]\d{14}(\d{2}[\dx])?/i;//? 0个或表示可有可无 身份证有15位和18位2种
        }
        function checkId() {
            var id = $("id").value;
            var reg = /^[1-9]\d{14}(\d{2}[\dx])?/i;//? 0个或表示可有可无 身份证有15位和18位2种
            if(!reg.test(id)){
                $("idInfo").innerText="请输入正确的身份证号码";
                $("idInfo").className="error";
                return false;
            }else{
                $("idInfo").innerText="√";
                $("idInfo").className="ok";
                return true;
            }
        }
        function checkInput() {
            // return false;
            return checkUsername() && checkPassword() && checkRepassword() && checkBirthday() && checkPhone() && checkMail() && checkId();
        }
        function $(id) {
            return document.getElementById(id);
        }
    </script>
</head>
<body>
<h2>用户注册</h2>
<form action="javascript:alert('注册成功!')" onsubmit=" return checkInput()">
    <table>
        <tr>
            <td>用户名:</td>
            <td>
                <input type="text" name="username" id="username" placeholder="请输入用户名" onblur="checkUsername()">
                <span id="usernameInfo"></span>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <input type="password" name="password" id="password" placeholder="请输入密码" onblur="checkPassword()">
                <span id="passwordInfo"></span>
            </td>
        </tr>
        <tr>
            <td>确认密码:</td>
            <td>
                <input type="password" name="repassword" id="repassword" placeholder="请再次输入密码" onblur="checkRepassword()">
                <span id="repasswordInfo"></span>
            </td>
        </tr>
        <tr>
            <td>身份证号码:</td>
            <td>
                <input type="text" name="id" id="id" placeholder="请输入身份证号码" onblur="checkId()">
                <span id="idInfo"></span>
            </td>
        </tr>
        <tr>
            <td>出生日期:</td>
            <td>
                <input type="text" name="birthday" id="birthday" placeholder="请输入出生日期" onblur="checkBirthday()">
                <span id="birthdayInfo"></span>
            </td>
        </tr>
        <tr>
            <td>手机号:</td>
            <td>
                <input type="text" name="phone" id="phone" placeholder="请输入手机号" onblur="checkPhone()">
                <span id="phoneInfo"></span>
            </td>
        </tr>
        <tr>
            <td>邮箱:</td>
            <td>
                <input type="text" name="mail" id="mail" placeholder="请输入邮箱" onblur="checkMail()">
                <span id="mailInfo"></span>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: left">
                <input type="submit" value="注   册">
                <input type="reset" value="重   置">
            </td>
        </tr>
    </table>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是叽叽呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值