JavaScript入门

来源:互联网 发布:程序员工资高吗 编辑:程序博客网 时间:2024/06/04 22:47

1 Javascript入门
1.1 引入
html:负责网页结构
css: 负责网页美观
javascript:负责用户与浏览器交互。
1.2 javacript的来由
1994时,网景公司研发了livescript语言,领航者浏览器(把livescript语言植入到浏览器)
微软公司的IE浏览器,后来自己花钱20亿美金研发jscript
1995年,Sun公司,推出jdk1.1 .谈合作。livescript-》javascript
1998,美国在线收购网景。
2003,直接关闭网景。网景6-7亿美金。2千万美金,组建谋智基金(火狐)
javascript jscript 语法不同。 ECMA(欧洲制造商联盟)
scirpt的语法:
1)基础语法(ECMA规范)
2)BOM编程(没有统一)
3)DOM编程(没有统一)
2.1 javascript使用
1.注释及常用函数

javascript的注释:单行 //   多行  /* */    css的注释:css  多行注释  /* */    html的注释:<!--注释 -->    常用的函数:        alert("提示框");        document.write("向浏览器输出内容");

2.javascript的使用方法:
1)内部javacript:
2)外部javascript(推荐使用)
2.2变量和数据类型

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/jscript">/*1.2 变量和数据类型                   1)定义和赋值变量: var 变量名=值;            var a = 10;            //var a = 20;            var b = 3.14;            var c = 'c';            var d = "hello";            var e = true;            var f = new Object();        注意:            1)使用var关键词定义变量,var可以省略的,但是不建议省略var            2) 在js中可以重复定义变量,后面定义的变量会覆盖前面的变量。            3) js是弱类型语言,使用var来定义任何数据类型            4)js中变量的类型是由变量的值决定的,所以只定义不赋值的变量,就是一个未赋值变量(undefined),            未赋值的变量不能使用        typeof(变量): 查看变量的数据类型        2)js的数据类型分类:            a)number: 无论整数还是小数,都是number类型            b) string:  无论字符还是字符串,都是string类型            c) boolean            d) object  对象类型                 */        var a = 100;        var b = 12.24;        var c = 'f';        var d = "abc";        var e = true;        var f = new Object();        document.write("a:"+typeof(a)+"<br>");        document.write("b:"+typeof(b)+"<br>");        document.write("c:"+typeof(c)+"<br>");        document.write("d:"+typeof(d)+"<br>");        document.write("e:"+typeof(e)+"<br>");        document.write("f:"+typeof(f)+"<br>");</script></head><body></body></html>

2.3 类型转换函数

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*1.3 类型转换函数 string->number(整数) :  parserInt(变量) string->number(小数):  parserFloat(变量)*/    var a = "100";    var b = "12.34";    document.write("a转换之前的类型"+typeof(a)+"<br>");    document.write("a转换之后的类型"+typeof(parseInt(a))+"<br>");    document.write("b转换之前的类型"+typeof(b)+"<br>");    document.write("b转换之后的类型"+typeof(parseFloat(b))+"<br>");</script></head><body></body></html>

2.4 运算符
1)算术运算符: + - * / %
2)比较运算符: > < >= <= ==
3)逻辑运算符: && || !
4)三目运算符: 表达式 ? true的结果 : false的结果

2.5 流程控制语句

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*    if语句        if(表达式){            语句          }else{            语句        }        条件可以是:            布尔值:true:成立 ; false:不成立            number:非0:成立; 0: 不成立            string: 非空字符串: 成立 ; 空字符串: 不成立            object: 非null: 成立;  null:不成立    */    /*if(true){        alert("条件成立");        }else{            alert("条件不成立");            }            */    /*    swtich语句        swtich(变量){        case 选项1:            语句;            break;  如果不break,就会继续下面选项的语句            case 选项2::            语句;            break;        default:            默认;        }        注意:            case的条件:                1)可以是常量. string,number                2)可以是变量。(java是不能是变量)                3)可以是表达式 (java不能这样)    */    /*var choice="a";    var a="a";    switch(choice){        //case的条件是一个变量        case a:        document.write("您选择了a");        break;        //case的条件是一个常量        case "b":        document.write("您选择了b");        break;        case "c":        document.write("您选择了c");        break;        case "d":        document.write("您选择了d");        break;        default:        document.write("您选择了其他");        break;        }*/        //case的条件是一个表达式,注意要写Break语句,注意case后面是个冒号        /*var age=18;        switch (true){            case age>=18:            document.write("你是个成年人了");            break;            case age<18:            document.write("你还没有成年,你好年轻。");            break;            }*//*    for语句:        for(初始化语句;条件判断语句;流程控制语句){            循环体语句        }        */    //需求:页面上打印十次helloworld    //需求:对1-100进行求和    /*for(var i=0;i<10;i++){        document.write("helloworld");        document.write("<br>");        }*/        /*var result=0;        for(var i=0;i<=100;i++){            result+=i;            }            document.write(result);            document.write("<br>");            *//*    while语句        初始化语句        while(条件判断语句){         循环体语句;        条件控制语句;        }        执行流程:        需求:在页面上打印十次helloworld;    */    /*var i=0;    while(i<10){        document.write("helloworld");        document.write("<br>");        i++;}*/        /*    do-while语句        初始化语句;        do{            循环体语句;            条件控制语句;        }while(判断条件语句)    需求:在页面上打印十次helloworld;    */    var i=0;    do{        document.write("helloworld");        document.write("<br>");        i++;}        while(i<10)</script></head><body></body></html>

with语句:方便函数的调用(以上练习题网页拿过来直接讲解)
with(对象){
直接写对象的方法,无需写对象的名称
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*      with语句:方便函数的调用(以上练习题网页拿过来直接讲解)        with(对象){            直接写对象的方法,无需写对象的名称           }            */            //输出10次helloworld,当对某一个对象使用频繁时可以使用这种方法            var i=0;            with(document){                while(i<10){                    write("helloworld");                    write("<br>");                    i++;}}</script></head><body></body></html>

2.6 函数

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*    js中的函数定义:    function 函数名(形式参数列表){函数体}    函数定义中需要注意的问题:    1.在js中函数的定义的参数列表不需要写var    2.js中的函数可以有返回值,无需声明返回值类型,只需要通过return这个关键字返回结果即可    3.js中没有方法重载的概念,如果方法名相同,后面的方法就会覆盖前面的方法    4.在我们js中的每一个函数中都存在一个arguments数组,这个数组就是用来接受我们的所有的实际参数的,接收完毕之后    给我们的函数的形式参数从左到右依次赋值    js函数的调用:    1.如何调用:函数名称(实际参数)    2.实际参数个数<形式参数个数   NaN      3.实际参数个数>形式参数个数   会拿着你的所有的实际参数给你的形式参数从左到右依次赋值,后面多余的形式参数直接舍弃*///定义一个俩个数相加function add(a,b){    alert(arguments.length);//接收实际参数,显示实际参数的个数    res=a+b;    return res;    }    //add函数的调用        var sum=add(1,2,5);        document.write(sum);//输出3        document.write("<br>");        var sum2=add(1);        document.write(sum2);//输出nan</script></head><body></body></html>

举个例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*    案例:定义一个函数,输入月份,可以查询到该月份的天数    1,3,5,7,8,10,12  大月 31天        4,,6,9,11  小月  30天        2  小小月  28天*///当我的按钮的单击事件被触发以后需要执行的操作function checkMonth(){        //获取单行输入域内的用户输入的月份值    var i=document.getElementById("month").value;        if(i==1||i==3||i==5||i==7||i==8||i==10||i==12){            alert("该月有31天");            }            else if(i==4||i==6||i==9||i==11){            alert("该月有30天");            }            else if(i==2){            alert("该月有28天");            }            else{                alert("您输入的月份有误,请重新输入");                }    }</script></head><body><div>请输入您要查询的月份:<input type="text" id="month"/><!--在这里需要给我的button标签添加一个单击事件,单击事件的名称就是方法名,注意还要加括号--><input type="button" value="查询" onclick="checkMonth()"/></div></body></html>

2.7 基于对象编程
1.String对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*    1.String对象            方式一:定义String对象            var str1 = new String("hello");            var str2 = new String("hello");            document.write("结果:"+(str1==str2)+"<br/>");            valueOf():该方法返回对象的内容            document.write("结果:"+(str1.valueOf()==str2.valueOf()));            方式二:            var str1 = "hello";            var str2 = "hello";             document.write("结果:"+(str1==str2)+"<br/>");        常用方法:            charAt(索引): 返回指定索引的内容            indexOf(字符串): 返回首次出现指定字符的索引位置            lastIndexOf(字符串): 返回最后出现指定字符的索引位置            fontcolor("red"): 直接给字符串添加颜色            split("字符串"): 使用指定字符串切割字符串,返回字符串数组            substring(start,end); 截取字符串,start:开始索引, end:结束索引            substr(strat,[length]) 截取字符串, start:开始索引 length: 截取的字符串长度            */            //方法一:定义String对象            var str1=new String("hello");            var str2=new String("hello");            //比较的是俩者的地址值            document.write(str1==str2);            document.write("<br>");            //比较的是俩者的内容            document.write(str1.valueOf()==str2.valueOf());            document.write("<hr>");            //方法二:定义String对象            var str3="hello";            var str4="hello";            //因为没有new ,所以直接比较的是内容,即结果为true            document.write(str3==str4);            document.write("<hr>");            //charAt(索引): 返回指定索引的内容            document.write(str1.charAt(2));            document.write("<br>");            //indexOf(字符串): 返回首次出现指定字符的索引位置            document.write(str1.indexOf("o"));            document.write("<br>");            //lastIndexOf(字符串): 返回最后出现指定字符的索引位置            document.write(str1.lastIndexOf("l"));            document.write("<br>");            //fontcolor("red"): 直接给字符串添加颜色            document.write(str1.fontcolor("yellow"));            document.write("<br>");            document.write("<hr>");            //split("字符串"): 使用指定字符串切割字符串,返回字符串数组            //新定义一个字符串            var str5="java-i-love-u";            //切割为一个个字符串组成字符数组            var arr=str5.split("-");            for(var i=0;i<arr.length;i++){                document.write(arr[i]);                document.write("<br>");                }            //substring(start,end); 截取字符串,start:开始索引, end:结束索引            document.write(str3.substring(1,3));            document.write("<br>");            //substr(strat,[length]) 截取字符串, start:开始索引 length: 截取的字符串长度            document.write(str3.substr(0,3));            document.write("<br>");</script></head><body></body></html>

2.Number对象,Boolean对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*Number对象            方式一:定义Number对象            var num1 = new Number(20);            var num2 = new Number(20);            方式二:            var num1 = 20;            var num2 = 20;            对比            document.write((num1==num2)+"<br/>");            document.write(num1.valueOf()==num2.valueOf());            Boolean对象            var b1 = new Boolean(true);            var b2 = new Boolean(true);            document.write((b1==b2)+"<br/>");            document.write(b1.valueOf()==b2.valueOf());*/            //方法一:定义Number对象,在这里要注意Number是一个对象,第一个字母要大写            var num1=new Number(14);            var num2=new Number(14);            document.write(num1==num2);//false            document.write("<br>");            document.write(num1.valueOf()==num2.valueOf());//true            document.write("<br>");            //方法二:定义Number对象            var num3=20;            var num4=20;            document.write(num3==num4);//true            document.write("<br>");            document.write(num3.valueOf()==num4.valueOf());//true            document.write("<br>");            //定义boolean对象            var b1 = new Boolean(true);            var b2 = new Boolean(true);            document.write("<br>");            document.write((b1==b2));//false            document.write("<br>");            document.write(b1.valueOf()==b2.valueOf());//true</script></head><body></body></html>

3.Math对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*Math对象            常用的方法:            1)ceil(): 向上取整。 如果有小数部分的话,直接+1            2)floor(): 向下取整。如果有小数部分的话,直接丢失小数部分,保利整数位            3) round(): 四舍五入取整。满5进一            4)random(): 生成一个随机的0-1的小数 .包含0,不包含1            5)max(): 返回最大值            6)min(): 返回最小值             var num = 3.50;            document.write(Math.ceil(num)+"<br/>");            document.write(Math.floor(num)+"<br/>");            document.write(Math.round(num)+"<br/>");            document.write(Math.round(Math.random()*100)+"<br/>");            document.write(Math.max(10,6,54,23,76)+"<br/>");            document.write(Math.min(10,6,54,23,76)+"<br/>");*/var num=3.14;document.write(Math.ceil(num));document.write("<br>");document.write(Math.floor(num));document.write("<br>");document.write(Math.round(num));document.write("<br>");document.write(Math.random()*100+1);document.write("<br>");document.write(Math.max(12,334));document.write("<br>");document.write(Math.min(13,56,565));document.write("<br>");</script></head><body></body></html>

举个例子:网页版的猜数字小游戏

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">//生成一个随机数    var ran=Math.floor(Math.random()*100+1);    alert(ran);function checkNumber(){    var num=document.getElementById("num").value;    num=parseInt(num);    if(num>ran){        alert("您猜测的数字小了");        }        else if(num<ran){            alert("您猜测的数字大了");            }            else if(ran==num){                alert("您猜对了,恭喜您");                }    }</script></head><body>请输入您要猜测的数字:<input type="text" id="num" /><!--创建一个单击事件--><input type="button" value="猜"  onclick="checkNumber()"/></body></html>

4.Date对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript" >/*    Date对象            //创建日期            var date = new Date(); //取当前系统日期时间    java: SimpleDateFormat对象 yyyy-MM-dd 格式化            //document.write(date);  //默认格式            //格式: 2015年06月01日 15时12分30秒            //年份            document.write(date.getFullYear()+"年");            //月            document.write((date.getMonth()+1)+"月");            //日            document.write(date.getDate()+"日");            //星期            document.write("星期"+date.getDay()+"&nbsp;");            //时            document.write(date.getHours()+"时");            //分            document.write(date.getMinutes()+"分");            //秒            document.write(date.getSeconds()+"秒");*/            //创建一个date对象,注意这里的Date也是一个对象,所以第一个字母要大写            var date=new Date();            document.write(date);            document.write("<br>");            document.write(date.getYear());//这个方法已经过时了,不用了。            document.write("<br>");            //年份            document.write(date.getFullYear()+"年");            //月份            document.write(1+date.getMonth()+"月");//这里要注意月份是从0开始计数的,所以要加1            //日期            document.write(date.getDay()+"日"+"&nbsp;&nbsp;");            //时            document.write(date.getHours()+"时");            //分            document.write(date.getMinutes()+"分");            //秒            document.write(date.getSeconds()+"秒");</script></head><body></body></html>

举个例子:网络时钟

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title></head><body><span id="spanTime"></span></body><script type="text/javascript">/*案例练习:网页时钟*///创建一个方法,获取当前时间function getTime(){    //获取标签对象    var spanTime=document.getElementById("spanTime");    //创建一个日期对象    var date=new Date();    //将他的日期按特定的格式拼接    var time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"&nbsp;&nbsp;"+date.getHours()+"-"+date.getMinutes()+"-"+date.getSeconds();    //var time=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDay()()+"&nbsp;&nbsp;"+date.getHours()+"-"+date.getMinutes()+"-"+date.getSeconds();    //document.write(time);    //给标签体设置内容,为=time    spanTime.innerHTML=time;    }    //getTime();//这样的方式对上面设置时间的方法只调用了一次,所以我们的时间无法实现动态的设置变化    window.setInterval("getTime()",1000);    //参数1:调用的函数名称   参数2:每隔多久调用一次,调用的次数没有限制</script></html>

5.Array数组对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">/*            Array数组对象                   方式一:创建数组                1.1 指定数组长度                var arr = new Array(3);                1.2 不指定数组长度、默认0个元素                var arr = new Array();                1.3 指定具体内容                var arr = new Array(10,"hello",true);                方式二: 不需要new,直接指定内容                var arr = [10,"java",false];                注意:                1)数组的长度会随着元素的添加而变化,不用担心出现索引位置越界的异常。                2) js的数组可以存放任意类型的元素。                常用的方法:                join(字符串): 使用指定的字符串,把数组的所有元素连接在一起,最终组成一个新的字符串                reverse(): 反转数组中的元素                常用的属性:length 数组的长度                    for-in语句(数组讲完之后再讲,和普通for循环遍历对比):                    for(var 遍历 in  数组){                    }                    var arr = [10,20,30,40];                    作用:遍历数组                     需求:定义数组进行遍历*/                    //创建数组指定长度                    var arr1=new Array(3);                    arr1[0]=100;                    arr1[1]=200;                    arr1[3]=300;                    arr1[4]=400;                    //创建数组不指定长度                    var arr2=new Array();                    arr2[0]="hello";                    arr2[1]=100;                    arr2[3]="java";                    arr2[4]=200;                    //指定具体内容                    var arr3=new Array("hello",100,false);                    //不需要new,直接指定内容                    var arr4=["hello",100,true,200];                    //遍历数组                    for(var i=0;i<arr4.length;i++){                        document.write(arr4[i]);                        document.write("<br>");                        }              //join(字符串): 使用指定的字符串,把数组的所有元素连接在一起,最终组成一个新的字符              document.write("<hr>");              var arr5=["java","hello","world"];              var str2=arr5.join("-");              document.write(str2);              document.write("<br>");             //reverse(): 反转数组中的元素              var arr6=arr4.reverse();              for(var i=0;i<arr6.length;i++){                        document.write(arr6[i]);                        document.write("<br>");                        }</script></head><body></body></html>
原创粉丝点击