JavaScript(JS)

来源:互联网 发布:美丽港发型设计软件 编辑:程序博客网 时间:2024/05/01 08:34

一  JS的简介

            JavaScript是基于对象和事件驱动的脚本语言,主要应用在客户端。

            基于对象:提供好了很多对象,可以直接拿过来使用

            事件驱动:HTML做网站静态效果,JavaScript动态效果

            客户端:专门指的是浏览器

            特点:交互性(信息的动态交互)

                       安全性(不可以直接访问本地磁盘)

                       跨平台性(只要是可以解析JS的浏览器都可以执行,和平台无关)

            JavaScript和Java的区别:

                    1  Java是sun公司,现在是Oracle;js是网景公司

                    2  JavaScript是基于对象的,Java是面向对象的

                    3  Java是强类型的语言,JS是弱类型的语言

                                   比如Java里面  int ="10";

                                   js:var i=10;var m="10";

                    4  JavaScript只需解析就可以执行,而Java需要先编译成字节码文件,再执行

            JavaScript的组成(三部分)

                 ECMAScript

                         ECMA:欧洲计算机协会—制定JavaScript语法

                BOM:

                         broswer  object model    浏览器对象模型

                DOM:

                         document object model  文档对象模型

二  JS和HTML的结合方式

          1  使用一个标签<script type="text/javascript">js代码</script>

          2  使用script标签,引入一个外部的js文件

                   创建一个js文件,demo.js

                   使用此方式的时候,就不要在script标签里写js代码了,不会执行

demo.js代码

alert("第二种方式");

html代码

<html><head><title></title></head><script type="text/javascript">alert("第一种方法");</script><script type="text/javascript" src="demo.js"></script><body></body></html>

三  JS的原始类型和变量声明

            Java的基本数据类型:byte,short,int,long,float,double,char,double

            js的原始类型:

                   stringL字符串

                             var  str="abc";

                   number:数字类型

                             var m=123;

                   boolean:true和false

                             var b=true;

                   null:var date = new Date();

                           表示获取一个对象的引用,null表示对象的引用为空,所有的对象的引用也是object

                   undifinedL:定义一个变量,没有赋值。var aa;

          typeof():查看的当前变量的类型

<html><head><title></title></head><script type="text/javascript">//定义一个字符串var str="abc";alert(str);//定义一个数字var m=123;alert(typeof(m));//定义一个布尔类型var  flag=true;</script><script type="text/javascript" src="demo.js"></script><body></body></html>

四  JS的语句

            Java里面的语句

                  if判断

                  switch语句

                  循环  for  while  do-while

            js里面的这些语句

                   if判断语句:

                         

                   switch语句:

                           Java里面支持数据类型。在JDK1.7开始支持string类型

                           js里面都支持

                            switch(a){

                                       case 5:

                                                   break;

                                       case 6:

                                                  break;

                                        ......

                                       default:

                               }

                   for:

                           

                   while:

                               

                   do-while:

<html><head><title></title></head><script type="text/javascript">var a=5;//if判断if(a==5)alert("5");elsealert("不是5")var b=6;//switch语句switch(b){case 3:alert("3");break;case 6:alert("6");break;default:alert("other");break;}//while语句var i=5;while(i>1){alert(i);i--;}//for循环for(var s=0;s<=5;s++){   //变量是var ,而不是intalert(s);}</script><body></body></html>

五  JS的运算符

           +=:   x+=y   ====>x=x+y 

            大部分运算与Java都一样,以下为不一样的

             在js里面不区分整数和小数

          字符串相加和相减的操作

          boolean:如果设置成true,相当于这个值是1;

                          如果设置成false,相当于这个值是0;

          ==和===的区别:都是做判断

               ==比较的是值;===比较的是值和类型

<html><head><title></title></head><script type="text/javascript">var a=123;alert(a/1000*1000);   //在Java里面得0,在js里得123,在js里面不区分整数和小数//字符串的操作var str="456";alert(str+1);//在Java和js里都是4561,正常的字符串链接alert(str-1);//相减的时候,执行减法的运算。得455//如果字符串不是数字,会提示NAN//boolean类型操作var flag=true;    //等于1alert(flag+1);var flag1=false;   //等于0alert(flag1+1);//==和===的区别var aa=5;if(aa==5){alert("5");}elsealert("other");var aa="5";if(aa===5){alert("5");}elsealert("other");</script><body></body></html>

六  99乘法表的练习

         

<html><head><title>实现99乘法表</title></head><body><script type="text/javascript">document.write("<table border='1' bordercolor='red'>");//document里面使用双引号,如果设置标签的属性需要使用单引号,document可是输出常量,变量还可以输出HTML标签//循环行for(var i=1;i<=9;i++){document.write("<tr>");for(var j=1;j<=i;j++){document.write("<td>");document.write(j+"*"+i+"="+j*i);document.write("</td>");}document.write("</tr>");}document.write("</table>");</script></body></html>

七  JS的数组

          什么是数组?

                使用变量,var m=10;

                java里面的数组,定义 int []  arr ={1,2,3};

          定义方式(三种)

                第一种:var arr=[1,2,3];     var arr=[1,"4",true];

                第二种:使用内置对象 Array      var  arr1=new Array(5) ;  //定义一个数组,长度为5.

                                                                   arr1[0]="1";

                第三种:使用内置对象Array

                              var arr2=new Array(3,4,5);   //定义一个数组,数组里面的元素是3,4,5

       数组里面有一个属性:length—获取数组的长度

       数组里面可以存放不同的数据类型的数据

<html><head><title>数组的定义方式</title></head><body><script type="text/javascript">//第一种方式定义数组var arr=[1,2,"3"];document.write("第一种方式"+arr+",数组的长度"+arr.length);//第二种方式定义数组var arr1=new Array(3);arr1[0]="a";arr1[1]="b";arr1[2]="c";document.write(",第二种方式"+arr1);//第三种方式定义数组var arr2=new Array(6,7,8);document.write(",第三种方式"+arr2);</script></body></html>

八  JS的函数

           在js里面定义函数(方法)有三种方法

           在函数的参数列表里面,不需要写var,直接写变量名称就可以

                    第一种:使用一个关键字function

                                    function 方法名(参数列表){

                                                  方法体;

                                                  返回值可有可无(根据实际需要)

                                    }          

                    第二种:匿名函数

                                     var add  =   function (参数列表){ 方法体和返回值}

                    第三种:动态函数(用得少)

                                   使用js里面的一个内置对象 Function

                                       var   add= new Funcrtion ("参数列表","方法体和返回值");    

九  JS的全局变量和局部变量

           全局变量:在script标签里定义一个变量,这个变量在页面中js部分都可以使用
           局部变量:在方法体内部定义一个变量,只能在方法体内部使用

<html><head><title>js的变量</title></head><body></body><script>\var aa=10;alert("在方法外面调用全局变量aa="+aa);function test(a,b){var nn=20;alert("在方法内面调用全局变量aa="+aa);alert("在方法内面调用局部变量nn="+nn);}test();//alert("在方法外面调用局部变量nn="+nn);   //不好使<script>alert("在另一个script里面调用全局变量aa="+aa);//alert("在另一个script里面调用局部变量nn="+nn);  //不好使</script></html>

十  script放的位置

          建议把script标签放到</body>后面
           如果现在有一个这样的需求:
                     在js里面需要获取到input里面的值,如果把script标签放在head里面
                     会出现问题
                     HTML解析是从上到下解析的,script标签放到的是head里面,直接在里面取input里面的值,
                    因为页面还没有解析到input那一行,肯定取不到。

十一  JS的重载的简单介绍

           什么叫重载?方法名相同,参数列表不相同

            js是否有重载?没有

<html><head><title>js的重载</title></head><body></body><script>function add1(a,b){return a+b;}function add1(a,b,c){return a+b+c;}function add1(a,b,c,d){return a+b+c+d;}alert(add1(2,2));  //NANalert(add1(2,2,2));   //NANalert(add1(2,2,2,2));    //8</script></html>

十二  JS的string对象

              创建String对象
                       var str="123";

             方法和属性(文档)
                       属性 length:字符串的长度

                       方法:
                            1 与HTML相关的方法
                                      bold():加粗
                                      fontcolor():设置字符串的颜色
                                      fontsize():设置字体的大小
                                      link():将字符串显示成超链接
                                      sub():下标
                                      sup():上标

<html><head><title>String</title></head><body></body><script>//length属性var str ="abcde";document.write(str.length);//bold方法document.write("<hr/>");var str1="jiacu";document.write(str1.bold());//fontcolordocument.write("<hr/>");var str2="字体颜色";document.write(str2.fontcolor("red"));//fontsize()document.write("<hr/>");var str3="zitidaxiao";document.write(str3.fontsize(5));//linkdocument.write("<hr/>");var str4="超链接";document.write(str4.link("hello.html"));//点击超链接到hello.html页面//sub和supdocument.write("<hr/>");var str5="100";var str6="200";var str7="300";document.write(str5.sub());document.write(str7);document.write(str6.sup());</script></html>


                            2 与Java相似的方法

                                      concat():链接字符串   

                                      charAt():返回指定位置的字符串
                                      indexOf():返回字符串位置
                                      split():把字符串切分成字符串数组
                                      replace():替换字符串
                                            传递两个参数:第一个参数是原始的字符,第二个是要替换成的字符
                                      substr():从第几位开始,向后截取几位
                                      substring():从第几位开始,到第几位结束,但不包含最后那一位
 

<html><head><title</title></head><body></body><script>//concat方法var str1="abc";var str2="efg";document.write(str1.concat(str2));//charAt() document.write("<hr/>");var str3="abcdefg";document.write(str3.charAt(0));  //如果字符的位置不存在,返回空字符串//indexOf()document.write("<hr/>");var str4="hijklmn";document.write(str4.indexOf("j")); //如果字符不存在,会返回-1//split()document.write("<hr/>");var str5="-b-c-d";var arr1=str5.split("-");document.write("分割后数组长度"+arr1.length);//replace()document.write("<hr/>");var str6="abcdefg";document.write(str6.replace("b","B"));//substr()和substring()document.write("<hr/>");var str7 ="abcdefghijklmn";document.write("substr的结果"+str7.substr(5,3)+"<br/>")  //fgh,从5开始向后截取三位document.write("substring的结果"+str7.substring(5,3));   //de  截取第三到第四位  [3,5)</script></html>

十三  JS的Array对象
       创建数组(三种)
            var arr1= [1,2,3];
            var arr2=new Array(3);//长度是3
            var arr3=new Array(1,2.3);//数组中的元素是1 2 3
       属性:length:查看数组的长度
      方法:
           concat():链接两个或更多的数组,并返回结果
           join():元素通过指定的分隔符进行分割
           push():表示向数组末尾添加一个或更多个元素,返回数组的新的长度
           pop();删除最后一个元素并且返回删除的那个元素
           reverse():颠倒数组中元素的顺序

<html><head><title>js的 Array对象</title></head><body></body><script>//length属性var arr1=[1,2,3];document.write(arr1.length);//concat()document.write("<hr/>");var arr11=[1,2,3];var arr12=[4,5.6];document.write(arr11.concat(arr12));//join()document.write("<hr/>");var arr2=new Array(3);arr2[0]="a";arr2[1]="b";arr2[2]="c";document.write(arr2); //默认以分号分隔各个元素document.write("<br/>");document.write(arr2.join("-"));//以-进行分隔//push()  也可以传进一个数组,把数组当做一个整体元素传进去,不管数组有多长,新的长度只加1,数组中的所有元素合并成一个整体document.write("<hr/>");var arr3=new Array(3);arr3[0]="tom";arr3[1]="lily";arr3[2]="lucy";document.write(arr3);document.write("长度为"+arr3.length);document.write("<br/>");document.write("新的长度"+arr3.push("jack"));//pop()document.write("<hr/>");var arr4=["zhangsan","lisi","wangwu","zhaoliu"+"<br/>"];document.write("old array:   "+arr4);document.write("return:   "+arr4.pop()+"<br/>");document.write("new array:  "+arr4);//reverse()document.write("<hr/>");var arr5=["aaaaa","bbbbb","cccc","dddd"];document.write("old array:   "+arr5+"<br/>");document.write("new array:   "+arr5.reverse());</script></html>

十四  JS的Date对象
        在Java里面获取当前时间
               Date date = new Date();
                   //格式化
                   //toLocaleString
js里面获取当前时间
               var date = new Date();

               toLocaleString():转换成本地形式的时间 
               getFullYear():得到当前的年,返回四位
               getYear():得到当前的年,返回两位

               getMonth():得到当前的月(返回的是值0-11)

              getDay():获取当前的星期(返回值0-6)星期日作为一周的第一天,返回的是0;

              getDate():获取当前的日(1-31)
              getHours():获取当前的小时(0-24)
              getMinutes():获取当前的分钟(0-59)

              getSeconds():获取当前的秒(0-59)

               getTime():获取毫秒数,返回的是1970年1月1日至今的毫秒数

              应用场景:第一次访问网站很快,第二次访问网站很快,由于缓存

             使用毫秒数来处理缓存的效果(没有缓存)

              http://www.baidu.com?毫秒数

<html><head><title>js的Date对象</title></head><body></body><script>//获取当前时间var date =new Date();document.write(date);//转换成习惯的格式document.write("<hr/>");document.write(date.toLocaleString());//得到当前的年document.write("<hr/>");document.write("year:  "+date.getFullYear());//获取当前的月document.write("<hr/>");var month=date.getMonth()+1;      //返回的是0—11document.write("Month:   "+month);  //获取当前的星期document.write("<hr/>");document.write("Week:  "+date.getDay());  //0-6//获得当前的日document.write("<hr/>");document.write("day:   "+date.getDate());//获取当前的小时document.write("<hr/>");document.write("hour:  "+date.getHours());//获取当前的分钟document.write("<hr/>");document.write("Minutes:   "+date.getMinutes());//获取当前的秒document.write("<hr/>");document.write("Seconds:   "+date.getSeconds());//获取当前的毫秒document.write("<hr/>");document.write("times:   "+date.getTime());</script></html>

十五  JS的Math对象

            数学的运算
                  不像Date,String等,不是对象的方法,是静态方法,使用可以直接使用Math.方法名称()
                   ceil(): 向上舍入
                   floor():向下舍入
                   round():四舍五入
                   random():得到随机数(伪随机数)(0.0-1.0)

<html><head><title>js的Math对象</title></head><body></body><script>var mm=10.4;document.write("old:   "+mm+"<br/>");//10.4document.write("ceil:   "+Math.ceil(mm)+"<br/>");  //11document.write("floor:   "+Math.floor(mm)+"<br/>");//10document.write("round:    "+Math.round(mm));//10//random()document.write("<hr/>");document.write(Math.random());//得到0-9的随机数document.write("<hr/>");document.write("0-9的随机数:  "+Math.floor(Math.random()*10));</script></html>

十六  JS的全局函数

           什么是全局函数?
                     不属于任何一个对象,直接使用名称使用
                eval():执行js代码(如果字符串是一个js代码,使用方法直接执行) 
                encodeURI():表示对字符进行编码
                decodeURI();对字符进行解码
                encodeURIComponent();
                decodeURIComponent():
                isNaN():返回true和false(不是数字返回true,是数字返回false)
                parseInt():类型转换

<html><head><title>js的全局函数</title></head><body></body><script>//eval()var  str="alert('eval方法');";eval(str);//encodeURI()document.write("<hr/>");var str1="测试中文aaaa123";  //中文编码var encode1=encodeURI(str1);document.write("编码:  "+encode1);//decode()document.write("<hr/>");document.write("解码:   "+decodeURI(encode1));//isNaN()document.write("<hr/>");var str2="123";document.write("isNaN:   "+isNaN(str2)+"<br/>");var str3="abcd";document.write("isNaN:   "+isNaN(str3));//parseInt():document.write("<hr/>");var str4="123";document.write("以字符串相加的形式:  "+str4+1+"<br/>"+"类型转换后:     ");document.write(parseInt(str4)+1);</script></html>

十七  JS的函数重载

           js的重载是否存在,不存在
                    调用最后一个方法
                    把传递的参数保存到arguments里
           面试:js里面是否存在重载?
                    1 JS里面不存在重载
                    2 但是可以通过其他方法模拟重载的效果:arguments

<html><head><title>js的函数重载</title></head><body></body><script>/*function add1(a,b){//alert("length:  "+arguments.length);for(var i=0;i<arguments.length;i++){alert("value:  "+arguments[i]);}return a+b;}*/function add1(){if(arguments.length==2){return arguments[0]+arguments[1];}else if(arguments.length==3){return arguments[0]+arguments[1]+arguments[2];}else if(arguments.length==4){return arguments[0]+arguments[1]+arguments[2]+arguments[3];}else{return 0;}}//调用document.write("两个参数结果为:"+add1(1,2)+"<br/>");document.write("三个参数结果为:"+add1(1,2,3)+"<br/>");document.write("四个参数结果为:"+add1(1,2,3,4)+"<br/>");document.write("五个参数"+add1(1,2,3,4,5));</script></html>

十八  JS的bom对象

          bom:broswer object model:浏览器对象模型
                 有哪些对象
                    navigator:获取客户机(浏览器)的信息
                    navigator.appName:浏览器的名称
                    screen:获取屏幕信息
                   location:请求的URL地址
                   href: 获取请求的URL地址
                   设置URL地址:页面上设置一个按钮,按钮上绑定一个时间,当我点击这个按钮,页面可以跳转到另外的压面
                   history:请求的url的历史记录
                   history.back():上一个页面
                   history.forward():下一个页面
                   history.go():传-1到上一个页面,传1到下一个页面
                   window:表示一个窗口对象
                           顶层对象(所有的bom对象都是在window里面操作的)
                      方法:
                         alert():页面弹出提示框
                         confirm():确认提示框,可传一个参数:显示的内容
                         prompt():输入对话框,可传两个参数:显示的内容和输入框里面的默认值
                         open():打开一个新的窗口,可传多个参数,
                                 第一个:打开新窗口的URL地址
                                 第二个:空
                                 第三个:窗口特征:高;宽
                        close():关闭窗口(浏览器兼容性比较差)
                        做定时器:
                        setInterval("js代码",毫秒数):
                                 window.setInterval("alert('123');",300);//代表每三秒执行一次alert
                       setTimeout("js代码",毫秒数):表示在毫秒数之后执行,但是只会执行一次
                                window.setTimeout("alert('在3秒后执行');",3000);
                       clearInterval():表示清除通过setInterval设置的定时器
                       clearTimeout():清除setTimeout设置的定时器
                      参数为setInterval何setTimeout返回的值:
                                var id1=setInterval("alert('23');",3000);
                                clearInterval(id1);

<html><head><title>js的bom对象 </title></head><body><input type="button" value="跳转" onclick="href1()"/><hr/><input type="button" value="open" onclick="open1()"/><hr/></body><script> document.write("navigator的用法: "+navigator.appName);document.write("<hr/>");document.write("screen的用法:  "+"<br/>屏幕的宽:"+screen.width+"  屏幕的高:"+screen.height);document.write("<hr/>");document.write("location的用法:<br/>当前的URL地址"+location.href);//href设置URL地址function href1(){//document.write("使用跳转按钮进入的页面");location.href="hello.html";}document.write("<hr/>");//confirm()var flag=confirm("confirm提示框");document.write("confirm有返回值:"+flag);document.write("<hr/>");//prompt()var pro = prompt("prompt输入框:请输入","0");document.write("prompt输入框输入的内容:"+pro);document.write("<hr/>");//open()function open1(){window.open("hello.html","","width=200,height=100");}</script></html>

十九  JS的dom对象

          dom:document object model:文档对象模型
                      文档:超文本文档(超文本标记文档)-html;xml

                      对象:提供了属性和方法
                      模型: 使用属性和方法操作超文本标记文档
                      可以使用js里面的DOM里面提供的对象,使用这些属性和方法,对标记型文档进行操作
                      想要对标记型文档进行操作,首先需要 对标记型文档里面的所有内容封装成对象
                      需要把HTML里面的标签,属性,文本内容都封装成对象
                             要想对标记型文档进行操作,解析标记型文档
                    如何使用DOM解析HTML

                     解析过程:
                          根据HTML的层级结构,在内存中分配一个树形结构,需要把HTML中的每部分封装成对象
                          document对象:整个文档
                          element对象:标签对象
                          属性对象
                          文本对象
 
                         Node节点对象:这个对象是这些对象的父对象
                                    如果在对象里面找不到想要的方法,这个时候到Node去找

二十  DHTML的简介

            DHTML:不是一种语言,是很多技术的简称(HTML CSS DOM JavaScript)
                   HTML:封装数据
                   CSS:使用属性和属性值设置样式
                   DOM:操作HTML文档(标记型文档)
                  JavaScript:专门指的是js的语法语句(ECMAScript)

二十一  document对象

           document对象:表示整个对象
                   每个载入的HTML文档都会成为document对象
          方法:
                write():向页面输出变量(值);向页面输出HTML代码
                getElementByID():通过id得到元素(标签),传递的参数是标签里面的id的值
                      得到属性值:标签对象.属性名称
                getElementsByName():通过name得到元素,返回的是一个集合
                getElementsByTagName():通过标签得到元素

<html><head><title>js的dom对象</title></head><body><input type="text" id="nameid" value="aaaa"/><br/><input type="text" name="name1" value="ccc"/><br/><input type="text" name="name1" value="ddd"/><br/><input type="text" name="name1" value="eeee"/></body><script>var input1=document.getElementById("nameid");document.write("<hr/>");document.write("通过id获取元素对象:"+input1+"<br/>");document.write("value的值:  "+input1.value+"<br/>")//向input里面设置一个nameinput1.name="bbbbbb";document.write("向input标签中设置name值: "+input1.name);document.write("<hr/>");var inputs = document.getElementsByName("name1");document.write("通过getElementsByName得到的集合的长度:"+inputs.length+"<br/>");//遍历数组for(var i=0;i<inputs.length;i++){//通过遍历数组,得到每个标签里面的具体的值document.write("输出得到的集合的第"+(i+1)+"个元素:"+inputs[i]+"<br/>");//每个元素的value值document.write("输出得到的集合的第"+(i+1)+"个元素:"+inputs[i].value+"<br/>");}document.write("<hr/>");var inputss = document.getElementsByTagName("input");//遍历数组for(var i=0;i<inputss.length;i++){//通过遍历数组,得到每个标签里面的具体的值document.write("输出得到的集合的第"+(i+1)+"个元素:"+inputss[i]+"<br/>");//每个元素的value值document.write("输出得到的集合的第"+(i+1)+"个元素:"+inputss[i].value+"<br/>");}</script></html>

二十二  案例window弹窗案例

          实现过程
                1 创建一个页面
                        有两个输入项和一个按钮
                        按钮上面有一个事件,弹出一个新窗口 open
                2 创建弹出的页面
                        表格
                       每一个有一个按钮和编号和姓名
                       按钮上有一个事件:把当前的编号和姓名,赋值到第一个页面相应的位置

open.xml

<html><head><title></title></head><body><table border="1" border-color="red"><tr><td>操作</td><td>编号</td><td>姓名</td></tr><tr><td><input type="button" value="选择" onclick="s1('001','张三')"/></td><td>001</td><td>张三</td></tr><tr><td><input type="button" value="选择" onclick="s1('002','赵四')"/></td><td>002</td><td>赵四</td></tr><tr><td><input type="button" value="选择" onclick="s1('003','王五')"/></td><td>003</td><td>王五</td></tr></table></body><script>/**/function s1(num1,name1){//需要把num1和name1赋值到window页面//跨页面的操作 opener:得到创建这个窗口的窗口,得到window页面var pwin = window.opener;pwin.document.getElementById("numid").value = num1;pwin.document.getElementById("nameid").value = name1;//关闭窗口window.close();}</script></html>

window.html

<html><head><title></title></head><body>编号:<input type="text" id="numid"/><br/>编号:<input type="text" id="nameid"/><br/><input type="button" value="选择" onclick="open1()"/></body><script>//弹出窗口的方法function open1(){window.open("open.html","","width=250,height=150");}</script></html>


二十三  window弹窗案例需要注意的地方

           由于我们现在访问的是本地文件,JS安全性,谷歌浏览器安全级别很高,不允许访问本地文件
           在实际开发中,没有这样的问题,实际开发中不可能访问本地的文件

二十四  案例—在末尾添加节点

             

<html><head><title>在末尾添加节点</title></head><body><ul id="ulid"><li>1111</li><li>2222</li><li>3333</li><li>4444</li></ul><input type="button" value="添加" onclick="add1();"/></body><script>//在末尾添加节点function add1(){//获取元素var ul1 = document.getElementById("ulid");//创建标签var li1 = document.createElement("li");//创建文本var text1 = document.createTextNode("5555");//把文本加入到li下面li1.appendChild(text1);//把li加入到ul下面ul1.appendChild(li1);}</script></html>

二十五  elementt对象

            要操作element对象,首先必须要获取到element
                   使用document里面相应的方法获取
            方法
                   获取属性里面的值:getAttribute()
                   可以用户获取getElementById()获取不了的关键字的属性值:class;id
                   设置属性的值:setAttribute()
                   删除属性:removeAttribute()
                  不能删除value

<html><head><title>element对象</title></head><body><input type="text" id="inputid" value="aaaa"/><hr/></body> <script>var input1=document.getElementById("inputid");document.write("用getAttribute获取value值"+input1.getAttribute("value"));input1.setAttribute("class","haha");document.write("<hr/>");document.write("用setAttribute设置之后的值"+input1.getAttribute("class"));</script></html>
         想要获取标签下面的子标签
      使用属性 childNodes,但是这个属性的兼容性太差

      获得标签下面的子标签的唯一有效办法,使用getElementsByTagName方法

<html><head></head><body><ul id="ulid"><li>aaaaa</li><li>bbbbb</li><li>ccccc</li></ul></body><script>//获取到ul下面的所有子标签(子元素)//获取ul标签var ul1 = document.getElementById("ulid");//获取ul下面的子标签var lis = ul1.childNodes;//兼容性很差document.write(lis.length+"<br/>");//ie为3,谷歌火狐为7var lis1 = ul1.getElementsByTagName("li");document.write("用getElementsByTagName方法:"+lis1.length);</script></html>

二十六  Node对象的属性

        nodeName
        nodeType
        nodeValue
        使用dom解析html时候,需要html里面的标签,属性和文本都封装成对象
        标签结点对应的值

                   nodeName:1
                   nodeType:大写标签名称 比如SPAN
                   nodeValue:null
         属性节点对应的值
                  nodeName:2
                  nodeType:属性名称
                  nodeValue:属性的值
        文本节点对应的值
                  nodeName:3
                  nodeType:#text
                  nodeValue:文本内容

<html><head></head><body><span id="spanid">哈哈哈哈哈</span><hr/></body><script>//获取标签对象var span1 = document.getElementById("spanid");document.write(span1.nodeType+"<br/>");//1document.write(span1.nodeName+"<br/>");//SPANdocument.write(span1.nodeValue+"<hr/>");//null//属性var id1 = span1.getAttributeNode("id");document.write(id1.nodeType+"<br/>");//2document.write(id1.nodeName+"<br/>");//iddocument.write(id1.nodeValue+"<hr/>");//spanid//文本var text1 = span1.firstChild;document.write(text1.nodeType+"<br/>");//3document.write(text1.nodeName+"<br/>");//#textdocument.write(text1.nodeValue+"<hr/>");//哈哈哈哈哈</script></html>

<html><head></head><body><ul id="ulid"><li id="li1">qqqqq</li><li id="li2">ppppp</li><li id="li3">wwwww</li><li id="li4">mmmmm</li></ul><hr/></body><script>/*父节点:ul是li的父节点parentNode子节点li是ul的子节点childNodes:得到所有的子节点,但是兼容性很差firstChild:获得第一个子节点lastChild:获得最后一个子节点同辈节点li之间关系是同辈节点*/var li1 = document.getElementById("li1");var ul1 = li1.parentNode;document.write("获取父节点ul的id:"+ul1.id);document.write("<hr/>");//获取ul的第一个子节点var ul11 = document.getElementById("ulid");var li11 = ul11.firstChild;document.write("使用firstChild得到第一个子节点:"+li11.id+"<br/>");var li14 = ul11.lastChild;document.write("使用lastChild得到最后一个子节点:"+li14.id+"<hr/>");//获得兄弟节点var li3 = document.getElementById("li3");document.write("获得li3的下一个兄弟节点:"+li3.nextSibling.id+"<br/>");document.write("获得li3的上一个兄弟节点:"+li3.previousSibling.id);</script></html>

二十七  操作DOM树

           appendChild方法
添加子节点到末尾
特点:类似于剪切的效果
insertBefore()方法
在某个节点之前插入一个新的节点
两个参数:
newNode:要插入的节点
oldNode:在谁之前插入

         removeChild:删除节点
         replaceChild:替换节点
         cloneNode(boolean):复制节点

<html><head><style type="text/css">#div1{width:200px;height:150px;border:2px solid red;}#div2{width:250px;height:150px;border:5px dashed green;`}</style></head><body><div id="div1"><ul id="ulid1"><li id="li11">lily</li><li id="li12">mary</li><li id="li13">jack</li></ul></div><div id="div2"></div><input type="button" value="add" onclick="add1();" /><input type="button" value="insert" onclick="insert1();"/><input type="button" value="remove" onclick="remove1();"/><input type="button" value="replace" onclick="replace1();"/><input type="button" value="copy" onclick="copy1();"/></body><script>function add1(){//得到div2var div2 = document.getElementById("div2");//获取ulvar ul1 = document.getElementById("ulid1");div2.appendChild(ul1);}function insert1(){//在mary之前添加一个人/*1 获取li12标签2 创建li3 创建文本4 把文本添加到li下面5 获取到ul6 把li添加到ul下面*/var li13 = document.getElementById("li12");var li14 = document.createElement("li");var text = document.createTextNode("lucy");li14.appendChild(text);var ul11 = document.getElementById("ulid1");ul11.insertBefore(li14,li12);}function remove1(){/*获取到要删除的节点获取其父节点删除*/var li13 = document.getElementById("li13");var ul12 = document.getElementById("ulid1");ul12.removeChild(li13);}function replace1(){//将lily替换为other/*1 获取到要替换的liA2 创建li的标签3 创建文本4 把文本添加到li的下面5 获取父节点ul6 完成替换*/var li11 = document.getElementById("li11");var li111 = document.createElement("li");var text = document.createTextNode("other");li111.appendChild(text);var ul13 = document.getElementById("ulid1");ul13.replaceChild(li111,li11);}function copy1(){//把ul复制到另一个div上/*1 获取到ul2 执行复制方法3 把复制之后的内容放到div上面获取到divappendChild方法*/var ul14 = document.getElementById("ulid1");var ulcopy = ul14.cloneNode(true);var div2 = document.getElementById("div2");div2.appendChild(ulcopy);}</script></html>

二十八  innerHTML属性

         这个属性不是dom的组成部分,但是大多数浏览器都支持的属性
               第一个作用:获取标签里面的文本内容
               第二个作用:向标签里面设置内容(可以是html代码)

<html><head><style type="text/css">#div11{width:200px;height:150px;border:2px dashed red;}</style></head><body><span id="sid">哈哈哈哈</span><div id="div11"></div><hr/></body><script>var span1 = document.getElementById("sid");document.write("通过innerHTML获取内容"+span1.innerHTML);document.write("<hr/>");//向div里面设置内容<h1>AAAAA</h1>var div11 = document.getElementById("div11");div11.innerHTML = "<h1>AAAAA</h1>"</script></html>

二十九  案例—动态显示时间

          得到当前的时间
          var date = new Date();
         var d1 = date.toLocaleString();
        需要让页面每一秒获取时间
         setInterval方法
       显示到页面上
        每一秒向div里面写一次时间
        使用innerHTML属性

<html><head><style type="text/css">#times{width:200px;height:150px;border:2px dashed red;}</style></head><body><div id="times"></div></body><script>function getD1(){var date = new Date();var d1 = date.toLocaleString();var div1 = document.getElementById("times");div1.innerHTML = d1;}setInterval("getD1();",1000);</script></html>

三十  案例—全选练习

        使用复选框上面一个属性判断是否选中

checked属性

            checked=true :选中,反之,不选中

         创建一个页面
复选框和按钮
四个复选框表示爱好
还有一个复选框操作,全选和全不选,有一个事件
三个按钮,分别有事件
全选
全不选
反选

<html><head></head><body><input type="checkbox" id="boxid" onclick="selAllNo();"/>全选/全不选<br/><input type="checkbox" name="love"/>篮球<br/><input type="checkbox" name="love"/>排球<br/><input type="checkbox" name="love"/>羽毛球<br><input type="checkbox" name="love"/>乒乓球<hr/><input type="button" value="全选" onclick="selAll();"/><input type="button" value="全不选" onclick="selNo();"/><input type="button" value="反选" onclick="selOther();"/></body><script>function selAll(){/*1 获取要操作的复选框2 返回的是数组属性 checked判断复选框是否选中遍历数组,得到每一个复选框checkbox设置其属性checked=true*/var all = document.getElementsByName("love");for(var i = 0;i<all.length;i++){var all1 = all[i];all1.checked = true;}}function selNo(){var all = document.getElementsByName("love");for(var i = 0;i<all.length;i++){var all1 = all[i];all1.checked = false;}}function selAllNo(){var check = document.getElementById("boxid");if(check.checked==true)selAll();elseselNo();}function selOther(){var all = document.getElementsByName("love");for(var i = 0;i<all.length;i++){var all1 = all[i];if(all1.checked == false)all1.checked = true;elseall1.checked = false;}}</script></html>

三十一  案例—下拉列表左右选择

          下拉选择框
创建一个页面
两个下拉选择框
设置属性multiple
四个按钮

<html><head></head><body><select id ="s1" multiple="multiple" style="width:100px;height:150px"><option>11111</option><option>22222</option><option>33333</option><option>44444</option><option>55555</option><option>66666</option></select><select id ="s2" multiple="multiple" style="width:100px;height:150px"><option>AAAAA</option><option>BBBBB</option><option>CCCCC</option><option>DDDDD</option><option>EEEEE</option><option>FFFFF</option></select><hr/><input type="button" value="选中添加到右边>>" onclick="selToRight()"/><input type="button" value="全部添加到右边>>" onclick="allToRight()"/><br/><input type="button" value="选中添加到左边<<" onclick="selToLeft()"/><input type="button" value="全部添加到左边<<" onclick="allToLeft()"/></body><script>function selToRight(){/*1 获取s1里面的option2 判断是否被选中属性 selected3 如果是选中4 得到s25 appendChild方法*/var select1 = document.getElementById("s1");var select2 = document.getElementById("s2");var options1 = select1.getElementsByTagName("option");for(var i=0;i<options1.length;i++){var option1 = options1[i];if(option1.selected==true){select2.appendChild(option1);i--;}}}function allToRight(){var select1 = document.getElementById("s1");var select2 = document.getElementById("s2");var options1 = select1.getElementsByTagName("option");for(var i=0;i<options1.length;i++){var option1 = options1[i];select2.appendChild(option1);i--;}}function selToLeft(){var select1 = document.getElementById("s1");var select2 = document.getElementById("s2");var options2 = select2.getElementsByTagName("option");for(var i=0;i<options2.length;i++){var option2 = options2[i];if(option2.selected==true){select1.appendChild(option2);i--;}}}function allToLeft(){var select1 = document.getElementById("s1");var select2 = document.getElementById("s2");var options2 = select2.getElementsByTagName("option");for(var i=0;i<options2.length;i++){var option2 = options2[i];select1.appendChild(option2);i--;}}</script></html>

三十二  案例—省市联动

   

<html><head></head><body><select id ="country" onchange="add1(this.value);"><option value="0">--请选择--</option><option value="中国">中国</option><option value="美国">美国</option><option value="日本">日本</option></select><select id ="city" ></select></body><script>//创建一个数组存储数据var arr = new Array(3);arr[0]=["中国","北京","吉林","哈尔滨","辽宁"];arr[1]=["美国","华盛顿","底特律","休斯顿","纽约"];arr[2]=["日本","东京","北海道","大阪","广岛"];function add1(val){/*1 遍历二维数组2 得到也是一个数组3 拿到的数组中的第一个值和传递过来的值作比较4 如果相同,获得到第一个值后面的元素5 得到city的select6 添加过去,appendChild方法创建option由于每次都要向city里面添加option第二次添加,会追加每次添加之前,判断一下city里面是否有option,如果有,删除*/var city = document.getElementById("city");var options = city.getElementsByTagName("option");for(var m=0;m<options.length;m++){var op = options[m];city.removeChild(op);m--}for(var i=0;i<arr.length;i++){var arr1 = arr[i];var firstvalue = arr1[0];if(firstvalue == val){for(var j=1;j<arr1.length;j++){var value1=arr1[j];var option1 = document.createElement("option");var text1 = document.createTextNode(value1);option1.appendChild(text1);city.appendChild(option1);}}}}</script></html>

三十三  案例—动态生成表格

        

<html><head></head><body>行: <input type="text" id="row">列: <input type="text" id="col"><br/><input type="button" value="生成" onclick="make();"><hr/><div id="divv"></div></body><script>function make(){/*1 得到输入的行和列的值2 生成表格循环行在行里面循环单元格3 显示到页面上*/var rows = document.getElementById("row").value;var cols = document.getElementById("col").value;var tab = "<table border='1' bordercolor='red'>";for(var i=1;i<=rows;i++){tab +="<tr>";for(var j=1;j<=cols;j++){tab +="<td>aaaaa</td>";}tab +="</tr>";}tab +="</table>";var divv = document.getElementById("divv");divv.innerHTML=tab;}</script></html>





0 0