魔鬼字典 JavaScript 笔记 代码比较多乱

  //2005中ctrl+J 有可能出提示

  //文本编辑出注释的快捷键

  名词解释:

  {

  //Java: 爪哇语言, 在因特网世界范围的 web 网页运转的以网络为基础的编程语言 (计算机用语)

  //Script : 手稿, 剧本, 手迹

  //cs结构: 客户端应用程序,用户需要下载客户端,例如QQ

  //BS结构: 浏览器应用程序,具有远程服务器,例如网页

  脚本语言:解释性语言,不进行编译,只在运行至相应代码时进行解释

  }

  完整的JavaScript组成

  {

  核心:ECMAScript

  文档对象模型:DOM /*Document/*文件*/ Object Model*/

  浏览器对象模型:BOM /*Browser /*浏览器*/ Object Model*/

  }

  JavaScript作用

  {

  提供用户交互

  动态更改内容

  数据验证

  }

  //建站:文件→新建→网站→ASP.NET 网站→位置(文件系统)→语言(Visual C#)→路径(添加合适路径储存网页)

  //添加HTML网页:(在资源管理器)添加新项→HTML页→起名→确定

  //自动生成的HTML中第一行(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">)表示生成文档类型

  //添加script标签:

  {

  位置:可以添加在任何位置,但是一般添加在<head></head>标签中

  格式:

  类型:

  {

  内嵌脚本: 放在<head></head>标签中并且有JavaScript文本

  例子:<script type="text/javascript" language="javascript">此处添加JavaScript文本</script>

  ↑

  文本类型

  外挂脚本(建议使用): 放在<head></head>标签中,没有方法体,只有地址

  例子:<head>

  <title>无标题页</title>

  <script type="text/javascript" language="javascript" src="waigua.js">

  </script> ↑

  </head> 地址 扩展名:.js

  添加→添加新项→JScript文件→起名→添加

  JScript文件中的内容:document.write("能看见呢?");

  }

  }

  //方法

  {

  document: document.write("这是我的第一个Js文本") /*相当于Console.WriteLine*/

  声明变量: var

  例子:var number=55;

  强制转换类型:

  {

  parseFloat(ppp)/*强制转换为float类型,ppp为变量名*/ !注意:parseFloat的拼写和大小写,如果在页面加载时出现错误则程序不向下运行!

  Boolean()强制转换,当参数为空字符串和null时,得到false :例子: document.write(Boolean(100)+"<br/>"); /*强烈注意Boolean的大小写!!!*/

  var color="violet";

  document.write(color.length,"<br/>"); /*强烈注意length的大小写!!!*/

  var num=10;

  document.write("10的二进制数为",num.toString(2),"<br/>"); 10的二进制数为1010 /*强烈注意toString的大小写!!!*/

  document.write("10的八进制数为",num.toString(8),"<br/>"); 10的八进制数为12

  document.write("10的十进制数为",num.toString(10),"<br/>"); 10的十进制数为10

  document.write(Number(testFunction())+"<br/>"); NaN /*NaN:非数字*/

  document.write(Number("123.12")+"<br/>"); 123.12

  document.write(Number(false)+"<br/>"); 0

  document.write(Number(true)+"<br/>"); 1

  document.write(parseInt("10")+"<br/>"); 10 /*parse:解析; 符合语法*/

  document.write(parseInt("56.6")+"<br/>"); 56

  var str="marssion"; /*typeof运算符,返回变量的类型*/

  document.write(typeof(str)+"<br/>"); 显示:string

  var temp;

  document.write(typeof(temp)+"<br/>"); 显示:undefined /*undefined : 未定义的*/

  var myObject={x:0,y:0};

  document.write(typeof(myObject)+"<br/>"); 显示: object

  document.write(typeof(null)+"<br/>"); 显示: object /*ECMAScript沿用了javascript中最初的一个错误,现在null被认为是对象的占位符,所以返回object,从技术上来讲仍是原始值。*/

  var oTemp;

  document.write((oTemp==undefined)+"<br/>"); 显示: true /*注意在比较时要加()否则比较时会把"<br/>"也加进去*/

  function testFunction(){} //如果函数没有实现则返回undefined值

  document.write((testFunction()==undefined)+"<br/>"); 显示:true /*函数给调用所以给加()*/

  document.write((null==undefined)+"<br/>"); 显示: true

  }

  }

  //调用函数

  {

  function a(Sname,Smessage) /*格式: function 函数名(参数1,参数2){函数体} 参数在定义时直接给名字就行了不需要指定类型*/

  {

  return Sname+Smessage;

  }

  var b=a("William","Welcome");

  document.write(b);

  }

  //if语句

  {

  var num=10;

  var num1="10";

  if(num==num1)

  {

  document.write("相等"); /*在比较不同类型的数据时,系统会自动的把两者的类型统一,或者把string类型转换成int或者把int转换成string再判断两者的关系*/

  }

  if(num!=num1)

  {

  document.write("不相等");

  }

  }

  //for语句

  {

  for(var a=1,b=0;a<101;a++) /*输出的是:5050*/

  {

  b+=a;

  }

  document.write(b);

  }

  //while语句

  {

  var a=1;var b=0; /*输出的是:5050*/

  while(a<101)

  {

  b+=a;

  a++;

  }

  document.write(b);

  }

  //do while 语句

  {

  var a=1; /*输出的是:5050*/

  var b=0;

  do

  {

  b+=a;

  a++;

  }while(a<101);

  document.write(b);

  }

  //alert 方法 和自定义属性 自定义object类型的变量 delete方法

  {

  var o=new Object(); /*定义一个oject类型的变量*/

  o.name="hellow word"; /*定义属性*/

  alert(o.name); /*alert :提防的,警惕的/*调用此方法弹出一个警告messagebox,()中写的是要显示的信息*/*/

  delete(o.name); /*delete 方法将引用变量的指针打断*/

  alert(o.name); /*o.name又变回undefined类型*/

  }

  //全等运算符(===)

  {

  var sNum="55";

  var tNum=55;

  document.write(sNum==tNum,"<br />"); 显示: true

  document.write(sNum===tNum,"<br />"); 显示: false /*“==”会将比较的双方自动类型转换成一样的类型再进行比较,“===”不会类型转换直接比较,int类型自然不等于string类型所以不相等*/

  document.write(sNum!=tNum,"<br />"); 显示: false

  document.write(sNum!==tNum,"<br />"); 显示: true

  }

  //switch

  {

  var date=new Date(); /*声明一个data类型的变量*/

  var time=date.getDay(); /*获得系统的当前日期*/

  switch(time)

  {

  case 0:

  document.write("星期日");

  break;

  case 1:

  document.write("星期一");

  break;

  case 2:

  document.write("星期二");

  break;

  case 3:

  document.write("星期三");

  break;

  case 4:

  document.write("星期四");

  break;

  case 5:

  document.write("星期五");

  break;

  case 6:

  document.write("星期六");

  break;

  }

  }

  /**/↑↓←→

  //arguments

  {

  function a(aa,bb,cc)

  {

  if(arguments.length==1) /*arguments.length属性: 计算调用函数时传过来的参数个数,可以模拟参数重载*/

  {

  document.write(aa+"<br/>"); /*argument[0] argument[1] argument[3] 能够代表()中的参数*/

  }

  else if(arguments.length==2)

  {

  document.write(aa+"~~~~~"+bb+"<br/>");

  }

  else if(arguments.length==3)

  {

  document.write(aa+" "+bb+" "+cc+"<br/>");

  }

  }

  a("william"); 显示:william

  a("william","welcome"); 显示:william~~~~~welcome

  a("william","welcome","myhouse"); 显示:william welcome myhouse

  }

  //with

  {

  var sMessage="hello world"; /*用了with后{}中不用再打相应的变量名了*/

  with(sMessage)

  {

  document.write(toUpperCase(),"<br />"); 显示:HELLO WORLD /*toUpperCase()方法是强打上去的,没有显示,所以要特别注意大小写*/

  document.write(length,"<br />"); 显示:11 /*length属性是强打上去的,没有显示,所以要特别注意大小写*/

  }

  }

  //void用法 /*没有返回值的*/

  {

  <body>

  <a href="javascript:void(window.open('about:blank'))">单击一下下</a> /*这是一个超级连接,打开一个新的窗体,不覆盖老窗体,如果没有void超级连接被点后“单击一下下”就会变成“[object]”有了void就不会变了*/

  </body>

  }

  //for in 用法 /*用于枚举对象的属性*/

  {

  var o=new Object();

  o.name="nameshuxing";

  o.age=21;

  o.gender="nan";

  随便起的变量

  ↓

  for(sss in o)

  {

  document.write(o[sss],"<br/>"); /*显示的是:nameshuxing 21 nan ,“document.write(sss)”输出的是属性的名字/*name age gender*/ “对象[属性名字]”显示的是相应属性的内容,就像hashtable中的查询一样*/

  }

  document.write("<b>window对象属性</b><br/>");

  for(aaa in document)

  {

  document.write(aaa,",<br/>");

  }

  }

  //闭包 /*函数嵌套*/

  {

  function test(num1,num2)

  {

  var num3=10;

  function inter(num4)

  {

  return num1+num2+num3+num4

  }

  return inter; /*这个return不能少,否则不能显示*/

  }

  var zhi=test(10,20);

  document.write(zhi(20)); /*显示:60*/ /*zhi(20)没有提示*/

  var aa="hello world";

  function a()

  {

  document.write(aa,"<br/>");

  }

  a(); /*显示:hello world* 必须调用/

  var num3=10;

  function b(num1,num2)

  {

  function bb()

  {

  return num1+num2+num3;

  }

  return bb;

  }

  var bbb=b(10,20);

  document.write(bbb()); /*显示:40*/

  }

  JS高级编程 第二章 对象 /**/↑↓←→

  //火狐浏览器能当计算器,输入“javascript:3-2”显示1,也可以写一些简单的Js语句,函数什么的

  //JavaScript在什么时间被执行

  {

  1、在文档被装载的时候

  2、文档加载后 /*在文档被加载后,<body>标记onload()时间发生,此时文档已经加载完毕*/

  3、被其他的JavaScript语句调用

  以下取自ajax and dot。Net2.0

  脚本装载周期:

  当网页被浏览器加载时,javascript在以下3个时间点被执行

  一:在文档被装载期间

  注意:此时文档还没有被加载,文档中的元素不能被使用。

  <html xmlns="http://www.w3.org/1999/xhtml" >

  <head runat="server">

  <title>My HTML Page</title>

  </head>

  <body>

  <h1>During load script execution</h1>

  <script type="text/javascript" language="javascript">

  alert("executing during page load.");

  </script>

  <h1>alert has executed!</h1>

  <form id="frmDefault" runat="server">

  <div>

  </div>

  </form>

  </body>

  </html>

  二:文档加载后

  在文档被加载后,<body> 标记 onload() 事件发生,此时文档已经加载完毕。

  <html xmlns="http://www.w3.org/1999/xhtml" >

  <head runat="server">

  <title>My HTML Page</title>

  </head>

  <script type="text/javascript" language="javascript">

  function alldone()

  {

  alert("all done!");

  }

  </script>

  <body onload="alldone();">

  <h1>After load script execution</h1>

  <h1>Final line...almost done!</h1>

  <form id="frmDefault" runat="server">

  <div>

  </div>

  </form>

  </body>

  </html>

  三:被其他的javascript语句调用

  }

  //对象的官方概念 :ECMA-262把对象定义为“属性的无序集合,每个属性存放一个原始值、对象或函数。”这意味着对象是无特定顺序的值的数组。

  //JavaScript对象分类

  {

  1、本地对象 例如:ECAM-262定义的对象:Object Functioin、Boolean、 Number 等

  2、内置对象 例如:Global对象、Math对象

  3、宿主对象 例如:所有DOM、BOM对象

  }

  //对象的创建

  {

  使用new关键字创建本地对象

  例如:var o=new Object();

  /*应用*/

  var car = new Object();

  car.name = "凯迪拉克";

  car.money = 1111111;

  document.write("我新买的" + car.name + "<br/>"); 显示: 我新买的凯迪拉克

  document.write("这破车花了我" + car.money + "<br/>"); 显示:这破车花了我1111111

  使用对象直接量创建

  例如:var oo={};

  var ooo={x:1,y:2};

  /*应用*/

  var obj = { x: 1, y: 2 } /*格式: var 对象名={ 属性名:值,属性名: 值......}*/

  for (mycar in obj) { /用对象直接量创建相当于创建一个函数(函数体内包含X Y(做成未赋值的属性))并用一个值初始化它并把属性赋值/

  document.write(mycar + "<br/>");

  }

  for (aaa in obj) {

  document.write(obj[aaa]+"<br/>");

  }

  /*显示*/

  x

  y

  1

  2

  }

  //对象的属性的表示方法

  {

  1、object.property

  2、object["property"]

  /*例子*/

  var car={x:1};

  car["color"]="黑色";

  car["name"]="宝马";

  car["price"] = 150000;

  var msg;

  for(msg in car) //调用方法显示出car中的所有属性的名称

  {

  msg+=" ";

  document.write(msg);

  }

  /*显示*/

  x color name price

  }

  //JavaScript本地对象

  {

  Object 类 /*ECMAScript中的所有类都由这个类继承而来 */

  {

  属性

  Constructor——对创建对象的函数的引用(指针)。对于Object类,该指针指向原始的object()函数(每个对象都有这个属性,它指向用来初始化该对象的构造函数)

  Prototype——对该对象的对象原型的引用。对于所有的类,它默认返回Object对象的一个实例。

  }

  Number 类 /*代表数值数据类型和提供数值常数的对象*/

  {

  创建:numObj=new Number(value) /*一般很少这样用,这么创建是引用类型的*/

  属性

  MAX_VALUE 属性|MIN_VALUE 属性|NaN 属性|NEGATIVE_INFINITY 属性|POSITIVE_INFINITY 属性|constructor 属性|prototype 属性

  方法

  toString 方法|valueOf 方法

  {

  /*例子*/

  var num1 = mynumber.valueOf();

  var num2 = mynumber.toString();

  document.write(num1, "<br/>"); /*显示:100*/ valueOf()和toString()在用法和结果上没什么区别

  document.write(num2,"<br/>"); /*显示:100*/

  }

  toFixed(int值)方法 /*保留几位小数,在银行中有用*/

  {

  /*例子*/

  var mynumber = new Number(100); /*显示:100.0000*/

  var num2 = mynumber.toFixed(4); /*保留四位小数*/

  document.write(num2, "<br/>");

  }

  Number.MAX_VALUE方法和Number.MIN_VALUE方法

  {

  /*例子*/

  var max = Number.MAX_VALUE;

  var min = Number.MIN_VALUE;

  document.write(max+"<br/>");

  document.write(min);

  /*显示*/

  1.7976931348623157e+308

  5e-324

  }

  }

  String类

  {

  语法:

  indexOf(“查找的子字符串”,查找的起始位置)

  返回子字符串所在的位置,如果没找到,返回 -1

  例如:

  var x

  var y=“abcdefg”;

  x=y.indexOf(“c” , 0 );

  //返回结果为2,起始位置是0

  /*例子及其他方法*/

  var str = new String("hello world 字符串示例");

  //Lenght属性

  document.write(str.length, "③<br />");//获取字符串的长度 /*显示:17③*/

  //charAt charCodeAt()

  document.write(str.charAt(0), "④<br />");//获取指定位上的字符 /*显示:h④*/

  document.write(str.charCodeAt(0), "<br />"); //获取指定位上的字符的ascii码 /*显示:104*/

  //concat() 与“+”号相同

  var oStringObject = new String("hello ");

  var sResult = oStringObject.concat("world");

  document.write(sResult, "⑤<br />"); /*显示:hello world⑤*/

  document.write(oStringObject, "⑥<br />"); /*显示:hello ⑥*/ //没有改变本身的值

  //indexOf() lastIndexOf()

  var myStr = new String("hello world");

  document.write(myStr.indexOf("o"), "⑦<br />"); /*显示:4⑦*/ //下标从0开始第一个“o”在下标4的位置上

  document.write(myStr.lastIndexOf("o"), "⑧<br />");//获取最后一个指定字符的位置 /*显示:7⑧*/ //下标从0开始从后数第一个“o”在下标7的位置上

  //slice() substring() //字符串的截取,两者不同的是“slice()”的()中可以放负数,“substing()”的()中如果放入负数则被系统看成0

  document.write(myStr.slice(3), "⑨<br />"); /*显示:lo world⑨*/ //第一个参数表示的从3开始截(包括3)没有第二个参数就有多长截多长

  document.write(myStr.substring(3), "⑩<br />"); /*显示:lo world⑩*/ //第一个参数表示的从3开始截(包括3)没有第二个参数就有多长截多长

  document.write(myStr.slice(3, 7), " 11<br />"); /*显示:lo w 11*/ //第一个参数表示的从3开始截(包括3)第二个参数表示截到下标7为止(不包括7)

  document.write(myStr.substring(3, 7), " 12<br />"); /*显示:lo w 12*/ //同上

  document.write(myStr.slice(-3), " 13<br />");//相当于slice(8) 字符串长度+参数 /*显示:rld 13*/ //可以接受负数,-3表示截取字符串中的最后3个

  document.write(myStr.substring(-3), " 14<br />");//负数相当于0 /*显示:hello world 14*/ //不能接受负数,系统自动转换成0,表示从0开始截,有多长截多长

  document.write(myStr.slice(3, -4), " 15<br />");//相当于slice(3,7) /*显示:lo w 15*/

  document.write(myStr.substring(3, -4), " 16<br />");//相当于substring(0,3)较小的数字放在第一个参数,位置自动转化 /*显示:hel 16*/

  //toLowerCase() toUpperCase() toLocaleLowerCase() toLocaleUpperCase() //转换大小写,toLocaleLowerCase() toLocaleUpperCase()是基于特定的区域实现的(一般用不上)

  document.write(myStr.toLowerCase(), " 17<br />"); /*显示:hello world 17*/

  document.write(myStr.toLocaleLowerCase(), " 18<br />"); /*显示:hello world 18*/

  document.write(myStr.toUpperCase(), " 19<br />"); /*显示:HELLO WORLD 19*/

  document.write(myStr.toLocaleUpperCase(), " 20<br />"); /*显示:HELLO WORLD 20*/

  //big() small()

  document.write(str.small()," 21<br />");//缩小字体

  document.write(str.big()," 22<br />");//放大字体

  //斜体字和删除线

  var ss=str.italics()+str.strike(); //italics()方法是将字体显示为斜体, strike()方法是在显示的字体上加上删除线

  document.write(ss);

  fontcolor();设定字体颜色

  /*例子*/

  var a = "换个字体颜色";

  a = a.fontcolor("red");

  document.write(a);

  sub();把字变成下标

  document.write("H"+"2".sub()+"O"); //这是字符串的方法,如果用var b = 2; b = b.sub();则行不通。

  }

  Math类

  {

  <meta http-equiv="refresh" content="2" /> //2秒自动刷新

  var test=Math.E;//表示自然对数的底

  document.write(test,"<br />"); /*显示:2.718281828459045*/

  test=Math.PI;

  document.write(test,"<br />"); /*显示:3.141592653589793*/

  document.write("2秒自动刷新,随机显示图片");

  var i = 0; //Math.random( ) :产生0-1的随机小数,Math.random()*10产生一个0-10的随机小数

  i=Math.round(Math.random()*10); //Math.round( ):四舍五入取整,如9.34 取整为9

  document.write("<img width=400 height=260 src=img/"+i+".jpg>");

  }

  Date类

  {

  var 日期对象 = new Date (年、月、日等参数)

  例:

  var mydate=new Date( “July 29, 1998,10:30:00 ”)

  如果没有参数,表示当前日期和时间

  例:

  var today = new Date( )

  方法

  {

  getYear(): 返回年数 getMonth():返回当月号数 getDate(): 返回当日号数 getDay():返回星期几 getHours():返回小时数 getMintes():返回分钟数 getSeconds():返回秒数 getTime() : 返回毫秒数

  setYear():设置年 setDate():设置当月号数 setMonth():设置当月份数 setHours():设置小时数 setMintes():设置分钟数 setSeconds():设置秒数 setTime ():设置毫秒数

  }

  /*例子*/

  //第一种参数

  var someDate=new Date(2008,05,20,12,00,00);

  document.write(someDate,"<br />");

  //第二种参数

  someDate=new Date("july 20 2008 12:30:30");

  document.write(someDate,"<br />");

  //获取系统当前日期

  var today=new Date();

  document.write(today,"<br />");

  document.write("某特定时间的星期为"+today.getDay()+"<br />");//0代表星期日

  document.write("某特定时间的日子为"+today.getDate()+"<br />");

  document.write("某特定时间的月份为"+(today.getMonth()+1)+"<br />");//月从0月开始 0代表十二月,0~11

  document.write("某特定时间的年份为"+today.getFullYear()+"<br />");

  document.write("某特定时间的小时为"+today.getHours()+"<br />");

  document.write("某特定时间的分钟为"+today.getMinutes()+"<br />");

  document.write("某特定时间的秒为"+today.getSeconds()+"<br />");

  //通过setDate方法修改日期,其他类似

  today.setDate(25);

  document.write("修改后的日期为"+today.getDate()+"<br />");

  /*显示*/

  Fri Jun 20 12:00:00 UTC+0800 2008

  Sun Jul 20 12:30:30 UTC+0800 2008

  Wed Aug 30 17:43:14 UTC+0800 2006

  某特定时间的星期为3

  某特定时间的日子为30

  某特定时间的月份为8

  某特定时间的年份为2006

  某特定时间的小时为17

  某特定时间的分钟为43

  某特定时间的秒为14

  修改后的日期为25

  /*实际用法*/

  var now = new Date();

  var hour = now.getHours();

  if (hour >= 0 && hour <= 12)

  document.write("上午好!")

  if (hour > 12 && hour <= 18)

  document.write("下午好!");

  if (hour > 18 && hour < 24)

  document.write("晚上好!");

  document.write("<P>今天日期:" + now.getYear() + "年"

  + (now.getMonth() + 1) + "月" + now.getDate() + "日"); //月份数字0-11,注意+1

  document.write("<P>现在时间:" + now.getHours() + "点" + now.getMinutes() + "分" + now.getSeconds() + "秒");

  /*显示*/

  下午好!

  今天日期:2006年8月30日

  现在时间:17点58分22秒

  //setTimeout() /*一次性定时器*/ 的用法

  {

  setTimeout(“调用的函数”,”定时的时间”)

  例:

  var myTime=setTimeout(”disptime( )”,1000); /*定时的时间是以毫秒为单位*/ //设定定时器

  clearTimeout(myTime); //解除定时器

  }

  setInterval() /*循环性计时器*/ 用法同上

  }

  }

  /**/↑↓←→

  //数组

  {

  声明数组三种方式

  第一种 var 数组名 = new Array(); /*赋值时用:数组名[数字]=值*/ /*数组的下标必须是大于0的数字否则就会被当成数组的一个属性对待*/

  例: var emp = new Array()

  第二种 var 数组名=new Array(5,4,3,2,1,”test”); /*数组中能放任何类型的元素*/

  第三种 var misc = [ 1.1, true, "a", ];

  var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]];

  /*理解*/

  function Circle(x,y,z)

  {

  this.x=x;

  this.y=y;

  this.z=z;

  }

  var c=new Circle(1,2,3);

  c[0]="this is an element";

  c[1]="this is an element";

  c[2]="this is an element";

  for(var temp in c)

  {

  document.write(c[temp],"<br />"); /*如果(c,"<br/>") 显示的是 x,y,z,0,1,2*/ //显示:1,2,3,this is an element,this is an element,this is an element

  } /*c[0]说是数组实际上也可以理解成属性,在Js中这两者的分界线并不是十分明显*/

  var test=new Array(1,2,3,4,5);

  for(var i=0;i<test.length;i++)

  {

  document.write(test[i],"<br />");

  }

  document.write("改变length的值前数组的长度:" + test.length, "<br />");

  test.length=3; /*数组的长度可以自己指定,指定的长度要是比原来的小:就自动把长出的部分自动砍掉,要是指定的长度比原来的长度长,多出的部分就是undefined(未定义)*/

  document.write(test, "<br />"); /*自动将元素用“,”连接*/

  document.write("改变length的值后数组的长度:" + test.length, "<br />");

  delete test[0]; /*用delete将数组的元素值删除,删除后的元素位置还在,只是没有值*/

  document.write(test, "<br />");

  document.write("使用delete后数组的长度:" + test.length);

  /*显示*/

  1

  2

  3

  4

  5

  改变length的值前数组的长度:5

  1,2,3

  改变length的值后数组的长度:3

  ,2,3

  使用delete后数组的长度:3

  JavaScript并不支持真正的多维数组,但是它允许使用元素为数组

  /*例子*/

  var table=new Array(3);//3行

  for(var i=0;i<table.length;i++)

  {

  table[i]=new Array(3);//每行3列

  }

  for(var row=0;row<table.length;row++)

  {

  for(var col=0;col<table[row].length;col++) /*数组之间的嵌套,赋值时:数组名[int][int]*/

  {

  table[row][col]=row*col;

  }

  }

  for(var r=0;r<table.length;r++)

  {

  for(var c=0;c<table[r].length;c++)

  {

  document.write(table[r][c]+" ");

  }

  document.write("<br />");

  }

  /*显示*/

  0 0 0

  0 1 2

  0 2 4

  //数组的方法

  {

  join()方法 : 该方法可以把一个数组的所有元素有转换成字符串,然后再把他们连接起来

  /*例子*/

  var test=[1,2,3];

  var s = test.join("-");

  document.write(test, "<br />");

  document.write(s, "<br />");

  /*显示*/

  1,2,3

  1-2-3

  reverse()方法 : 该方法将颠倒数组元素的顺序并返回颠倒后的数组

  /*例子*/

  var test=[1,2,3,4,5,6];

  test.reverse();

  for (var i = 0; i < test.length; i++) /*颠倒数组对原数组也进行了变动*/

  {

  document.write(test[i], "<br />");

  }

  /*显示*/

  6

  5

  4

  3

  2

  1

  sort()方法 : 该方法在原数组上对数组元素进行排序

  /*例子*/

  var fruits=["manago","orange","apple","strawberry"];//在元数组上进行排序

  var myFruits=fruits.sort();

  for(var i=0;i<myFruits.length;i++)

  {

  document.write(myFruits[i],"<br />"); /*排序对原数组也进行了改动,在对英文进行排序时,会比对第一个英文字母按照二十六个英文字母进行排序*/

  }

  for (var i = 0; i < fruits.length; i++) {

  document.write(fruits[i], "<br />");

  }

  var test=[33,4,611,222];

  test.sort(); /*直接用 数组名.sort()对数字数组进行排序时,并不是按照数字的大小进行排序,而是和英文排序一样,将数字的第一位拿出,按照大小进行排序*/

  for(var i=0;i<test.length;i++)

  {

  ocument.write(test[i],"<br />");

  }

  test.sort(function(a,b){return a-b;}); /*想对数字数组按照数字的大小进行排序时 test.sort(function(a,b){return a-b;}); 记住就这么用,方法中如果第一个参数应该出现在第二个参数之前那么比较函数就会返回一个小于0的数,如果第一个参数应该出现在第二个参数之后,那么比较函数就会返回一个大于0的数*/

  for(var i=0;i<test.length;i++) /*如果对一组字符串数组进行不分大小写的字母排序操作使用tolowerCase()*/

  {

  document.write(test[i],"<br />");

  }

  /*显示*/

  apple

  manago

  orange

  strawberry

  apple

  manago

  orange

  strawberry

  222

  33

  4

  611

  4

  33

  222

  611

  concat()方法 : 该方法能创建并返回一个数组

  /*例子*/

  var test=[1,2,3];

  document.write(test,"<br />");

  result = test.concat([8, 9]); /*添加时自动将[]去掉,只能去掉一层[],[5,[6,7]]添加后为5,[6,7]*/

  for(var i=0;i<result.length;i++)

  {

  document.write(result[i],"<br />"); /*使用此方法只是能在原有的数组基础上在创建一个数组,所以必须用一个变量接受,此方法对原数组没有影响*/

  }

  /*显示*/

  1,2,3

  1

  2

  3

  8

  9

  slice()方法 : 返回的是指定数组的子数组

  /*例子*/

  var test=[1,2,3,4,5,6];

  var result=test.slice(0,3); /*slice(0,3) : 0 :从索引0开始截, 3 :截到索引3为止(包括0不包括3),如果没有第二个参数就将剩下的全部删除*/

  for(var i=0;i<result.length;i++)

  {

  document.write(result[i],"<br />");

  }

  /*显示*/

  1

  2

  3

  splice()方法 : 该方法可以把元素从数组中删除,也可以将新元素插入到数组中,它在原数组上修改数组,并不创建新数组

  !只在firefox中能正确浏览! 注意:和concat()不同,splice()并不将它插入的数组参数展开,也就是说,如果传入的是一个数组插入的就是一个数组而不是这个数组的元素

  /*例子*/

  //IE浏览器无效,使用FireFox

  var test=[1,2,3,4,5,6,7,8];

  //删除元素

  var result = test.splice(4); //没有指定第二个参数表示从起始位置删至结尾,删除了5,6,7,8,将删除的数组返回

  for(var i=0;i<result.length;i++)

  {

  document.write(result[i],"<br />");

  }

  document.write("---------------------------<br />");

  for(var i=0;i<test.length;i++)

  {

  document.write(test[i],"<br />");

  }

  //添加元素

  document.write("---------------------------<br />");

  var test1=[1,2,3,4,5,6,7,8];

  //第二个参数表示要删除的元素数,0表示不删除,直接插入,非0表示删掉之后再插入

  var addResult=test1.splice(2,4,"liwei","marssion");

  for(var i=0;i<addResult.length;i++)

  {

  document.write(addResult[i],"<br />");

  }

  document.write("---------------------------<br />");

  for(var i=0;i<test1.length;i++)

  {

  document.write(test1[i],"<br />");

  }

  /*显示*/

  5

  6

  7

  8

  ---------------------------

  1

  2

  3

  4

  ---------------------------

  3

  4

  5

  6

  ---------------------------

  1

  2

  liwei

  marssion

  7

  8

  push()方法和pop()方法 //方法可以将一个或多个新元素附加到数组的尾部,然后返回数组的新长度,方法pop()将删除数组的最后的一个元素,减少数组的长度,返回它删除的值。

  //注意:这两个方法都是在原数组上修改数组,而非生成一个修改过的数组副本,联合使用push()和pop(),就可以用javascript实现一个先进后出的栈;

  /*例子*/

  var temp=[];

  document.write("Push<br />");

  temp.push(1, 2, 3, 4);

  document.write("数组元素有:"+temp+"<br />数组长度是:"+temp.length);

  document.write("<br />");

  document.write("Pop<br />");

  temp.pop();

  document.write("数组元素有:"+temp+"<br />数组长度是:"+temp.length);

  /*显示*/

  Push

  数组元素有:1,2,3,4

  数组长度是:4

  Pop

  数组元素有:1,2,3

  数组长度是:3

  unshift()方法和shift()方法 //方法unshift()会将一个或多个元素添加到数组的头部,然后把已有的元素移动到下标较大的位置以腾出空间,它返回的是数组的新长度;

  //方法shift()会删除并返回数组的第一个元素,然后将后面的所有元素都向前移动以填补第一个元素留下的空白

  /*例子*/

  //先进先出(FIFO)

  var test=[];

  document.write("Unshift<br />");

  test.unshift(1, 2, 3, 4);

  document.write(test,"<br />");

  document.write("Shift<br />");

  test.shift();

  document.write(test,"<br />");

  /*显示*/

  Unshift

  1,2,3,4

  Shift

  2,3,4

  instanceof运算符与typeof运算符相似,用于识别正在处理的对象的类型,不同的是,instanceof方法要求开发者明确地确定对象为某特定类型

  例:var ostring=new String(“hello”)

  document.write(ostring instanceof String); //返回一个boolean值,类型正确返回true否则返回false

  }

  }

  //对象的共同属性和方法

  {

  toString() //object类的方法,将非字符串转换成字符串

  toLocaleString() //object类的方法,返回对象本地化字符串,object默认的方法自身不做任何局部化,返回结果与toString()相同

  hasOwnProperty(property) //object类的方法,判断对象是否有某个非继承属性

  propertyIsEnumerable(property) //object类的方法,属性(非继承)是否可用 For in枚举

  isPropertyOf(object) //object类的方法,判断该对象是否为传入对象的原型

  }

  JS高级编程 第三章: Function 函数、类、构造函数、原型 Classes,Constructors,and Prototypes /**/↑↓←→

  //JS的断点: 在需要打断点的地方写上debugger , 在遇到版本不能调试时很可能是调试被禁用了:打开IE 工具→Internet选项→高级→浏览(将禁用脚本点没)

  //上节课补充

  {

  <SCRIPT language="JavaScript“>

  var a="3" , b="4";

  alert (a+"+"+b ); //输出的是: 3+4

  alert (eval(a+"+"+b) ); //输出的是: 7 eval("字符串"); eval()会将()中的代码进行动态解析,把代码解析成js脚本,不过尽量少用,因为怕有恶意脚本入注

  </SCRIPT>

  }

  //函数的定义(3种方法)

  {

  定义函数:

  function 函数名( 参数1,参数2,… )

  {

  语句;

  }

  如果函数不包含return语句,返回undefined

  var f = new Function("x", "y", "return x*y;"); //一般不用,效率太低

  等同于:

  function f(x, y) { return x*y; }

  var f=function(x){return x*x}

  函数直接量是一个表达式,他可以定义匿名函数/*匿名函数:函数在定义的时候没有名字,而用一个变量接受*/

  }

  //函数的调用

  {

  调用函数:使用运算符()来调用它 ;

  调用函数的注意事项

  (1)不能给函数的参数指定一个函数类型

  (2)JavaScript不会检测传递的数据是不是那个函数所要求的类型

  (3)也不会检测传递给他的参数个数是否正确

  }

  //函数的递归

  {

  var a = function aa(b) { //aa是方便后面调用

  if (b <= 1) {

  return 1;

  }

  return b * aa(b - 1);

  }

  document.write(a/*或aa*/(5)); //相当于:5*4*3*2*1 显示120

  }

  //函数并不只是一种语法,还可以是数据

  {

  var aa = new Array(3);

  aa[0] = function(x) {

  return x * x;

  }

  aa[1] = 20;

  aa[2] = aa[0](aa[1]);

  document.write(aa[2]); //显示:400

  }

  //做为方法的函数

  {

  var calculator={

  num1:1, !注意是“,”!

  num2:1,

  compute:function(){this.result=this.num1+this.num2;} //calculator相当于一个类 this.result相当于函数自定义了一个属性

  };

  //debugger

  calculator.compute();

  document.write(calculator.result,"<br />"); //显示:2 //calculator.result可能点不出来

  //this : 指向正在被调用的对象

  function aa() {

  return this.num11 * this.num22;

  }

  function bb(num1, num2) {

  this.num11 = num1;

  this.num22 = num2;

  this.a = aa;

  }

  var b = new bb(2, 3); //要用一个变量接受一下,这个事例是模仿的类,所以就要像真正的类一样用变量new一下然后才能点出

  document.write(b.a()); //显示:6

  }

  //Arguments

  {

  它是调用对象的一个特殊属性,能够计算出传入方法时实际参数的个数,它不是数组但可以用数组的方式操作它

  通过Arguments[]数组改变参数的值同样会改变用参数名获取的参数值

  /*例子*/

  function test(x,y,z) {

  try

  {

  if (arguments.length != 3) {

  throw new Error("未提供正确的参数个数"); //JS中的throw

  }

  else if (typeof (arguments[0]) != "number" || typeof (arguments[1]) != "number" || typeof (arguments[2]) != "number") {

  throw new Error("参数类型错误");

  }

  else {

  return x + y + z;

  }

  }

  catch(exception) //exception没有提示,硬打

  {

  document.write(exception.message); //exception.message也没有提示

  return ""; //不加return"";返回undefined

  }

  }

  document.write(test(1,2,"3"),"<br />");

  document.write(test(1));

  document.write(test(1,3,5));

  document.write("<br />");

  function fun(x)

  {

  document.write(x+"<br />");

  arguments[0]=null;//arguments[0] 命名参数x是引用同一变量的两种不同方法

  document.write(x);

  }

  fun(12);

  /*显示*/

  12

  null

  }

  //callee /*指向当前正在被执行的函数*/

  {

  function aa(x) {

  if(x<=1) {

  return 1;

  }

  return x + arguments.callee(x-1); /arguments.callee()指向的就是函数aa()/

  }

  document.write(aa(6)); /显示:21(6+5+4+3+2+1)/

  function aa(a, s, d) {

  document.write(arguments.length+"<br/>"); //显示: 1 //argument.length :实际参数的个数

  document.write(arguments.callee.length + "<br/>"); //显示: 3 //arguments.callee.length :形式参数的个数

  document.write(aa.length); //显示: 3 //函数名.length :形式参数的个数

  }

  aa(1)

  }

  //函数的方法

  {

  call() 方法

  f.call(o, 1, 2); //将f绑定到o "1,2"是f执行时需要的参数

  这与下面的代码相似:

  o.m = f;

  o.m(1,2);

  delete o.m;

  //call apply

  {

  function Add(x,y)

  {

  return x+y;

  }

  var o = new Object();

  document.write(Add.call(o,1,2),"<br />"); //绑定后直接返回值

  //类似于

  //o.m=Add;

  //o.m(1,2);

  //delete o.m;

  document.write(Add.apply(o,[1,2])); //给的是个数组,在但是在绑定时自动拆开 本事例的结果两者相同

  }

  }

  //模拟命名空间

  {

  if(typeof com=="undefined") //注意:undefined是字符串类型的要用“”

  {

  com=new Object(); //com前没有var

  }

  if(typeof com.sitepoint=="undefined") //个人觉得没什么用,可以用自己起的特别点的名字加_代替

  {

  com.sitepoint=new Object();

  }

  com.sitepoint.Bird=function()

  {

  this.feet=2;

  this.feathers=true;

  }

  var tweety=new com.sitepoint.Bird();

  alert("鸟有"+tweety.feet+"爪子");

  }

  //用new关键字创建对象

  {

  function Aa(w,h) //此示例模拟了一个类,this点出的方法做为本类的方法 注意:为了区分类和方法在命名时类的首字母要大写

  {

  this.width=w; //width作为本类的属性

  this.heigh=h;

  this.shuxing=function ()

  {

  return this.width*this.heigh;

  }

  }

  var a=new Aa(12,12); //没次new 都创建了一个新的对象,也重复创建了"shuxing"方法,浪费内存

  var b=new Aa(2,2);

  var c=new Aa(3,3);

  var cc=a.shuxing();

  document.write(cc);

  }

  //使用原型创建对象(调用prototype方法) //prototype:原型

  {

  function P(x, y)

  {

  this.x = x;

  this.y = y;

  this.total = function()

  {

  return this.x+this.y;

  };

  }

  P.prototype.z = 10; //添加对象P的原型属性 //用原型创建对象:原型对象或方法不在类中声明,在类的下面用:类名.prototype.属性名(或方法名)=值,声明后的属性和方法在调用时和普通属性方法没什么不同,只是在创建对象时不重复创建

  P.prototype.total1 = function(x, y)

  { //添加对象P的原型方法

  return x+y+1;

  };

  var t = new P(1, 2);

  var t1 = new P(3,4);

  t.z = 20; //动态添加属性,在java这种强类型语言中是不可能的……

  document.write(" total:"+t.total()+" total1:"+t.total1(1,3)+" z:"+t.z+"</br>");

  document.write(" total:"+t1.total()+" total1:"+t1.total1(2,4)+" z:"+t1.z+"</br>");

  /显示/

  total:3 total1:5 z:20

  total:7 total1:7 z:10

  }

  //模拟类的继承(call继承)

  {

  function jilei(q,w)

  {

  this.qq=q;

  this.ww=w;

  this.ii=function ()

  {

  return this.qq*this.ww;

  }

  }

  jilei.prototype.ee=function()

  {

  return this.qq+this.ww;

  }

  function zilei(r,t)

  {

  jilei.call(this,2,3); //绑定时用this代表本类

  this.rr=r;

  this.tt=t;

  }

  zilei.prototype.yy=function()

  {

  document.write(this.rr*this.tt);

  return""; //指定返回值为空否则返回undefined

  }

  var jj=new zilei(4,5);

  document.write(jj.ii()); //调用基类的方法不能点出只能硬打

  document.write(jj.yy());

  /显示/

  6

  20

  }

  /例子/

  『

  function xing(bian)

  {

  this.bianshuxing=bian;

  // this.jibianxing=function ()

  // {

  // document.write("这是一个"+this.bianshuxing+"形");

  // }

  }

  xing.prototype.jibianxing=function()

  {

  document.write("这是一个"+this.bianshuxing+"形");

  }

  function san(di,gao)

  {

  xing.call(this,3);

  this.d=di;

  this.g=gao;

  }

  san.prototype=new xing(); //在继承类的下面加上,让子类能够继承基类的所有属性包括原型方法

  san.prototype.s=function()

  {

  document.write("三角形的底是:"+this.d+"三角形的高是:" +this.g+"面积是:"+this.d*this.g/2);

  }

  function si(bian,bian3)

  {

  xing.call(this,4);

  this.bian1=bian;

  this.bian2=bian3;

  }

  si.prototype=new xing();

  si.prototype.ss=function()

  {

  document.write("四边形的一条边为:"+this.bian1+"四边形的第二条边为:"+this.bian2+"面积是:"+this.bian1*this.bian2);

  }

  debugger;

  var sanj=new san(4,3);

  sanj.jibianxing();

  sanj.s();

  var sibian=new si(7,8);

  sibian.jibianxing();

  sibian.ss();

  』

  //例子//

  {

  function xing(bian)

  {

  this.bianshuxing=bian;

  this.jibianxing=function ()

  {

  document.write("这是一个"+this.bianshuxing+"形");

  }

  }

  function san(di,gao)

  {

  xing.call(this,3);

  this.d=di;

  this.g=gao;

  }

  san.prototype.s=function()

  {

  document.write("三角形的底是:"+this.d+"三角形的高是:" +this.g+"面积是:"+this.d*this.g/2);

  }

  function si(bian,bian3)

  {

  xing.call(this,4); //this : 指示的是正在运行的程序,在类中是new出的类名指向的东东

  this.bian1=bian;

  this.bian2=bian3;

  }

  si.prototype.ss=function()

  {

  document.write("四边形的一条边为:"+this.bian1+"四边形的第二条边为:"+this.bian2+"面积是:"+this.bian1*this.bian2);

  }

  debugger;

  var sanj=new san(4,3);

  sanj.jibianxing();

  sanj.s();

  var sibian=new si(7,8);

  sibian.jibianxing();

  sibian.ss();

  /显示/

  {

  `这是一个3形三角形的底是:4三角形的高是:3面积是:6这是一个4形四边形的一条边为:7四边形的第二条边为:8面积是:56

  }

  }

  //不管用不用prototype方法创建,系统都会自动创建一个原型,里面有一个constructor对象,里面放的是一个指针,这个指针不随着类new出的对象里的元素的变化而变化,它能指向自己的基类

  『

  /例子/

  <script language="javascript" type="text/javascript">

  function Student(sName)

  {

  this.name=sName;

  this.displayName=function (){

  alert(this.name);

  }

  }

  function ZhangSan(sName,sAge)

  {

  this.method=Student;

  this.method(sName);

  delete this.method; //将delete this.method注释了也能正常运行,

  zhangsan new 出的对象虽然把method删除了,但是在new出的对象里面随着类的实例化的同时系统自动创建了一个原型,里面有一个指向基类(student类)的指针,所以在调用基类的方法时虽然她的method已经删除还是能找到基类的方法

  this.age=sAge;

  this.displayAge=function (){

  alert(this.age);

  }

  }

  var s1=new Student("普通学生");

  s1.displayName();

  var zs=new ZhangSan("张三",23);

  zs.displayName();

  zs.displayAge();

  </script>

  /例子/ /原型方法如果如果自己重新定义了一遍,再改变基类的原型方法后就不随着它的改变而改变了/

  『

  function Person(name,sex) { //Person类的构造函数

  this.name = name;

  this.sex = sex;

  }

  Person.prototype.age = 12; //为Person类的prototype属性对应的prototype对象的属性赋值,

  //相当于为Person类的父类添加属性

  Person.prototype.print = function() { //为Person类的父类添加方法

  alert(this.name+"_"+this.sex+"_"+this.age);

  };

  var p1 = new Person("name1","male"); //p1的age属性继承子Person类的父类(即prototype对象)

  var p2 = new Person("name2","male");

  p1.print(); //name1_male_12

  p2.print(); //name2_male_12

  p1.age = 34; //改变p1实例的age属性

  p1.print(); //name1_male_34

  p2.print(); //name2_male_12

  Person.prototype.age = 22; //改变Person类的超类的age属性

  p1.print(); //name1_male_34(p1的age属性并没有随着prototype属性的改变而改变)

  p2.print(); //name2_male_22(p2的age属性发生了改变)

  p1.print = function() { //改变p1对象的print方法

  alert("i am p1");

  }

  p1.print(); //i am p1(p1的方法发生了改变)

  p2.print(); //name2_male_22(p2的方法并没有改变)

  Person.prototype.print = function() { //改变Person超类的print方法

  alert("new print method!");

  }

  p1.print(); //i am p1(p1的print方法仍旧是自己的方法)

  p2.print(); //new print method!(p2的print方法随着超类方法的改变而改变)

  』

  JS高级编程 第四章 BOM ↑↓←→

  BOM(浏览器对象模型)

  浏览器对象分为

  {

  1、Window窗口对象(包含整个浏览器)

  2、Location地址对象(主要包含地址栏)

  3、Document文档对象(用Document.write()输出时显示的地方,占浏览器的大部分空间)

  4、Form表单对象(包含在文档对象中,由表单组成)

  }

  //window对象(Window对象表示整个浏览器窗口,但不必表示其中包含的内容,主要用于调整浏览器的大小)

  {

  window对象表示整个浏览器窗口

  moveBy(dx,dy)——把浏览器窗口相对当前位置水平移动dx个像素,垂直移动dy个像素。dx值为负数,向左移动窗口,dy值为负数,向上移动窗口。

  moveTo(x,y)——移动浏览器窗口,使它的左上角位于用户屏幕的(x,y)处。可以使用负数,不过这样会把部分窗口移出屏幕的可视区域。

  function click1() {

  window.moveTo(Math.random()*1000,Math.random()*1000);

  }

  resizeBy(dw,dh)——相对于浏览器窗口的当前大小,把它口的宽度调整dw个像素,高度调整dy个像素。dw为负数,把缩小窗口的宽度,dy为负数,缩小窗口的高度。

  resizeTo(w,h)——把窗口的宽度调整为w,高度调整为h。不能使用负数。

  窗口对象的方法主要用来提供信息或输入数据以及创建一个新的窗口。  创建一个新窗口open()使用window.open(参数表)方法可以创建一个新的窗口。其中参数表提供有窗口的主要特性和文档及窗口的命名。

  open(”打开窗口的url”,”窗口名”,”窗口特征”)

  窗口的特征如下,可以任意组合:

  top=# 窗口顶部离开屏幕顶部的像素数

  left=# 窗口左端离开屏幕左端的像素数

  width=# 窗口的宽度

  height=# 窗口的高度

  menubar=... 窗口有没有菜单,取值yes或no

  toolbar=... 窗口有没有工具条,取值yes或no

  location=... 窗口有没有地址栏,取值yes或no

  directories=... 窗口有没有连接区,取值yes或no

  scrollbars=... 窗口有没有滚动条,取值yes或no

  status=... 窗口有没有状态栏,取值yes或no

  resizable=... 窗口给不给调整大小,取值yes或no

  }

  //对话框

  {

  alert (“m提示信息") //显示包含消息的对话框。

  alert("第一种对话框"); //弹出一个警告框

  confirm(“提示信息”) //显示一个确认对话框,包含一个确定取消按钮 //confirm : 确定; 使巩固; 批准

  if(confirm("Are you sure?")) ()中写的是提示信息,此方法会返回一个Boolean值,点击确定返回TRUE,点击取消返回FALSE

  {

  alert("你点的yes"); //通常用法,当你点击确定时显示的信息

  }

  else

  {

  alert("你点的no"); //当你点击取消时显示的信息

  }

  Prompt(”提示信息“) //弹出提示信息框

  open ("url","name") //打开具有指定名称的新窗口,并加载给定 URL 所指定的文档;如果没有提供 URL,则打开一个空白文档,再加一个参数就是描述(打开的浏览器的宽、高....)

  close ( ) //关闭当前窗口

  /例子/

  <script type="text/javascript" language="javascript">

  var win;

  function openwindow() {

  win = open("http://www.sina.com","新浪","height=150,width=300,top=10,left=10,resizable=yes");

  }

  function closewindow() {

  win.close();

  }

  </script>

  </head>

  <body>

  <input type="text" id="txtname"/>

  <script language="javascript" type="text/javascript">

  文本框中的默认值

  ↓

  document.getElementById("txtname").value = prompt("请输入你的名字","qw");

  ↑

  脚本提示的文本

  </script>

  <input type="button" value="打开一个新的窗口" onclick="openwindow()"/>

  <input type="button" value="关闭刚才打开的窗口" onclick="closewindow()"/>

  </body>

  }

  defaultStatus status :设置浏览器最下端的状态栏,defaultStatus是持久性的,status是临时性的,注意:IE7默认情况下是将“允许状态栏通过脚本更新”设置为禁用的,可以在INternet选项-》安全性里修改此设置

  『

  <script language="javascript" type="text/javascript">

  function mystatus()

  {

  //window.defaultStatus = "你有没有注意我的存在??";

  window.status = "你有没有注意我的存在?";

  }

  </script>

  </head>

  <body onload="mystatus()">

  <a href="http://www.baidu.com" onmouseover="window.status='你有没有注意我的变化??';return true" onmouseout="window.status='你有没有注意我的存在??';return true">www.baidu.com</a>

  ↑ ↑

  注意用的是单引 分号和return true不能省略,return true可以防止地址出现在状态栏中

  </body>

  』

  history

  『

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function go_destination()

  {

  history.go(-1); //history.go(-1)和history.back()效果是一样的

  }

  function go_back()

  {

  history.back();

  }

  </script>

  </head>

  <body>

  <input type="button" onclick="go_destination()" value="上一页" />

  <input type="button" onclick="go_back()" value="上一页" />

  </body>

  Back ( ) 方法相当于后退按钮

  forward ( ) 方法相当于前进按钮

  go (1)代表前进1页,等价于forward( )方法;

  go(-1) 代表后退1页,等价于back( )方法;

  』

  Document对象

  『

  alinkColor 设置或检索文档中所有活动链接的颜色

  bgColor 设置或检索 Document 对象的背景色

  body 指定文档正文的开始和结束

  linkColor 设置或检索文档链接的颜色

  location 包含关于当前 URL 的信息

  title 包含文档的标题

  url 设置或检索当前文档的 URL

  vlinkColor 设置或检索用户访问过的链接的颜色

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function showTitle()

  {

  document.title="我不做大哥好多年"; //设置标题

  }

  function change(color)

  {

  document.bgColor=color;

  }

  </script>

  </head>

  <body>

  <input type="button" onclick="showTitle()" value="点击我显示标题" />

  <h2>移过来我变色show给你</h2>

  <span onmouseover="change('#CCCCCC')">变红色</span>

  <span onmouseover="change('blue')">变红色</span>

  <span onmouseover="change('yellow')">变红色</span>

  <img src="../js02/img/3.jpg"alt="" height="200" width="200" onmouseover="alert(document.images[0].src)" />

  <img src="../js02/img/4.jpg"alt="" height="200" width="200" onmouseover="alert(document.images[1].src)" />

  </body>

  cookie属性

  这里主要介绍一下cookie属性。cookie是当你浏览某网站时,网站存储在你机器上的一个小文本文件,它记录了你的用户ID,密码、浏览过的网页、停留的时间等信息,当你再次来到该网站时,网站通过读取cookie,得知你的相关信息,就可以做出相应的动作,如在页面显示欢迎你的标语,或者让你不用输入ID、密码就直接登录等等。

  cookie属性也包含了自己的一些属性值:

  expires:用来设置cookie的过期时间。

  domain:用来设置cookie的起作用的网站域名范围。

  path:用来设置cookie起作用的网站路径。

  secure:如果设置了这个属性,cookie的值只能在安全设置很高的环境下才能被读取。

  cookie的目的就是为用户带来方便,为网站带来增值。cookie属性也包含了自己的一些属性值:

  我们可以通过document.cookie操作来设置某个cookie值。

  』

  Location对象

  『

  属性

  host 设置或检索位置或 URL 的主机名和端口号

  hostname 设置或检索位置或 URL 的主机名部分

  href 设置或检索完整的 URL 字符串

  方法

  assign("url") 加载 URL 指定的新的 HTML 文档。

  reload() 重新加载当前页

  replace("url") 通过加载 URL 指定的文档来替换当前文档

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function jump()

  {

  location.href=document.myform.menu.value;

  }

  function jump1()

  {

  location.replace(document.myform.menu.value); //注意replace中放的是字符串给用"" //replace() 不记录历史即点完后不能后退

  }

  function jump2() {

  location.assign(document.myform.menu.value); //记录历史,可以后退

  }

  function showHost()

  {

  alert(location.host);

  }

  function showHostName()

  {

  alert(location.hostname);

  }

  function reLoad() {

  location.reload();

  }

  </script>

  </head>

  <body>

  <form name="myform" action="">

  <select name="menu" onchange="jump2()"><!--注意jump1的区别--> //<select> :下拉菜单 <option>每一个选项

  <option >-请选择-</option>

  <option value="test1.htm">犬夜叉</option>

  <option value="test2.htm">杀生丸</option>

  </select>

  <input type="button" value="显示主机名和端口号" onclick="showHost()" />

  <input type="button" value="显示主机名" onclick="showHostName()" />

  <!--<input />-->

  <input type="button" value="刷新" onclick="reLoad(true)" /><!--true表示从服务端加载false表示从缓存加载-->

  </form>

  </body>

  』

  Navigator //Navigator 对象是由 JavaScript runtime engine 自动创建的,包含有关客户机浏览器的信息(基本不用)

  『

  document.write(navigator.appCodeName, "<br />"); //与浏览器相关的内部代码名

  document.write(navigator.appName, "<br />"); //浏览器的正式名称

  document.write(navigator.appVersion, "<br />"); //浏览器的版本号

  document.write(navigator.browserLanguage,"<br />");//FireFox不支持

  document.write(navigator.cpuClass, "<br />"); //FireFox不支持,返回用户计算机的cpu的型号,通常intel芯片返回"x86"

  document.write(navigator.language,"<br />");//IE不支持

  document.write(navigator.platform, "<br />"); // 浏览器正在运行的操作系统平台

  document.write(clientInformation.appName);//微软特有的对象、

  /显示/

  Mozilla

  Microsoft Internet Explorer

  4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)

  zh-cn

  x86

  undefined

  Win32

  Microsoft Internet Explorer

  』

  //screen对象

  『

  availHeight——窗口可以使用的屏幕的高度(以像素计),其中包括操作系统元素(如Windows工具栏)需要的空间。

  availWidth——窗口可以使用的屏幕的宽度(以像素计)。

  colorDepth——用户表示颜色的位数。大多数系统采用32位。

  height——屏幕的高度,以像素计。

  width——屏幕的宽度,以像素计

  window.moveTo(0,0); //将浏览器调整到最左上角

  window.resizeTo(screen.availWidth,screen.availHeight,"<br />"); //将屏幕设置到最大化

  document.write(screen.availWidth + " " + screen.availHeight, "<br />"); //输出显示屏幕的可用最大宽和高 “开始状态栏占一部分”

  document.write(screen.height + " " + screen.width, "<br />"); //屏幕的最大高和宽

  document.write(" " + screen.colorDepth, "<br />");

  』

  //打开一个新的窗体

  『

  <SCRIPT language="JavaScript" >

  function openwindow( ) {

  var newWindow = window.open("about:blank", "newWindow", "toolbars=yes, scrollbars=yes, location=yes,statusbars=yes,menubars=yes,resizable=yes,width=650,height=150"); //()里面的东西给写对了否则读不出来实在不行用“"","",""”也行

  newWindow.document.open(); //流体打开

  newWindow.document.write("<html><head><title>极品名茶--铁观音</title></head>");

  newWindow.document.write("<body><h1>先生您好,来点铁观音尝尝吧?<a href=''>来点</a>    <a href=''>不了</a></h1></body></html>");

  newWindow.document.close(); //流体关闭

  }

  </SCRIPT>

  </head>

  <body onload="openwindow()">

  』

  //跨窗体传值↑↓←→

  『

  主窗体

  『

  <title>无标题页</title>

  <script type="text/javascript" language="javascript">

  function aa()

  {

  open("a2.htm","aaa","");

  }

  </script>

  </head>

  <body>

  <form name="f1" action="" method="post">

  ↑

  是name不是id,用id会有错误

  <input type="text" name="t1"/>

  <button onclick="aa()">sdf</button>

  </form>

  </body>

  』

  副窗体(a2.htm)

  『

  <title>无标题页</title>

  <script type="text/javascript" language="javascript">

  function bb()

  {

  document.f1.t2.value=window.opener.document.f1.t1.value;

  ↑

  f1后面的东西全部点不出来,都给硬打

  }

  </script>

  </head>

  <body onload="bb()">

  <form name="f1" action="" method="post">

  <input type="text" name="t2"/>

  </form>

  </body>

  』

  』

  JS 第五章 DOM(文本对象模型) ↑↓←→

  //节点类型

  『

  1、元素节点

  2、文本节点

  <p>段落</p> //<p>为元素节点,“段落”为文本节点

  』

  //节点的三个属性

  『

  nodeName节点元素名称

  nodeType节点元素类型(1-12)

  nodeValue节点元素的值

  1 element_node 2 attribute_node 3 text_node

  4 cdata_section_node 5 entity_reference_node 6 entity_node

  7 processing_instruction_node 8 comment_node 9 document_code

  10 document_type_node 11 document_fragment_node 12 notation_node

  『例子』

  『

  <a id="sirius" href="">Journey to the stars</a>

  -------------------------------------------------

  外置JS脚本:

  addLoadListener(init);

  function init()

  {

  var elementRef = document.getElementById("sirius");

  elementRef.firstChild.nodeValue = "sdfsd"; //将“Journey to the stars”动态的改变为“sdfsd” ; 注意要加上“firstChild”

  alert("The element is:" + elementRef.nodeName); //显示:A

  alert("The element is:" + elementRef.nodeType); //显示: 1

  alert("The element is:" + elementRef.firstChild.nodeValue); //显示:sdfsd

  return true;

  }

  function addLoadListener(fn)//注册事件函数

  {

  if(typeof window.addEventListener!="undefined")

  {

  window.addEventListener("load",fn,false);

  }

  else if(typeof document.addEventListener!="undefined")

  {

  document.addEventListener("load",fn,false);

  }

  else if(typeof window.attchEvent!="undefined")

  {

  document.attchEvent("onload",fn);

  }

  else

  {

  var oldfn=window.onload;

  if(typeof window.onload!="function")

  {

  window.onload=fn;

  }

  else

  {

  window.onload=function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  』

  』

  访问DOM中的元素

  『

  getElementById可以通过唯一的ID属性值 。

  getElementById很适合用于查找一个单独的元素

  <a id="sirius" href="sirius.html">Journey to the stars</a>

  var elementRef = document.getElementById("sirius");

  『例子』

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/GetElementByName.js">

  </script>

  <link rel="Stylesheet" type="text/css" href="css/GetElementByName.css" />

  </head>

  <body>

  <h1>Accessing elements</h1>

  <ul>

  <li><a href="test1.htm" name="myLink">Sirius</a></li>

  <li><a href="test2.htm" name="myLink">Canopus</a></li>

  <li><a href="test1.htm" name="myLink">Arcturus</a></li>

  <li><a href="test2.htm" name="myLink">Vega</a></li>

  </ul>

  </body>

  </html>

  --------------------------------------------------------

  外置JS脚本的内容:

  function init()

  {

  var anchors=document.getElementsByName("myLink");

  for(var i=0;i<anchors.length;i++)

  {

  anchors[i].className="starLink";

  }

  //return true;

  }

  『例子』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function myCopy() {

  var textBox1=document.getElementById("txt1");

  var textBox2=document.getElementById("txt2");

  textBox2.value=textBox1.value;

  ↑

  两个文本框中的文本相同

  }

  </script>

  </head>

  <body>

  <form id="myForm" action="" method="post">

  <input id="txt1" />

  <input type="button" value=">>>" onclick="myCopy()" /> //如果onclick()函数要是想调用两个以上的事件就在两个事件中间用“;”隔开

  ↑

  button上显示的字

  <input id="txt2" />

  </form>

  </body>

  </html>

  』

  JavaScript提供了通过标签名字来返回一组元素的方法:getElementsByTagName。

  <a href="sirius.html">Sirius</a>

  <a href="canopus .htm">canopus </a>

  <a href="arcturus .html">arcturus </a>

  <a href=“vega .html”>vega </a>

  var anchorArray = document.getElementsByTagName("a");

  『例子』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function myCopy()

  {

  var myArray = document.getElementsByTagName("input");//返回元素集合,()中放的是标记的名字,记住用“”

  var h2 = document.getElementsByTagName("h2");

  for(var i=0;i<myArray.length;i++)

  {

  if (myArray[i].type == "text") {

  myArray[i].value=h2[0].innerHTML; //"innerHTML"表示的是<h2></h2>中间包含的文本,点不出来只能硬打

  }

  }

  }

  </script>

  </head>

  <body>

  <form action="" method="post" id="myForm">

  <h2 id="h2">getElementsByTagName</h2><br />

  <input name="txt1" />

  <input name="txt1" />

  <input name="txt1" />

  <input id="btn" type="button" value="Click Me" onclick="myCopy()" />

  </form>

  </body>

  </html>

  』

  』

  //节点的访问顺序

  『

  node.childNodes 指定节点的所有子节点,包括文本节点和所有其他元素 //用法: 节点.childNodes 注意:打完不用加()

  node.firstChild 指定节点的第一个子节点

  node.lastChild 指定节点的最后一个子节点;

  node.parentNode 指定节点的上级节点;

  node.nextSibling 指定节点的下一个兄弟节点;

  node.previousSibling 指定节点的上一个兄弟节点

  『例子』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script type="text/javascript" language="javascript">

  function myDominspector()

  {

  var DOMString="";

  var DOMText="";

  var demolist=document.getElementById("eventsList");

  if(demolist==null) //判断:获得的集合是不是为空,或者是否成功获取

  {

  return;

  }

  if(demolist.hasChildNodes()) //hasChildNodes() 该方法能判断是否有子节点

  {

  var ch=demolist.childNodes; //如果有子节点用“ch”获得该集合 //绝大部分都给硬打,特别注意大小写

  for(var i=0;i<ch.length;i++)

  {

  DOMString+=ch[i].nodeName+"\n"; //获得子节点的标记名字

  DOMText+=ch[i].firstChild.nodeValue; //获得子节点的值,注意给加"firstChild"

  }

  document.write(DOMString);

  document.write(DOMText);

  document.write(ch[2].childNodes[0].firstChild.nodeValue); //因为“类表项三”用的是嵌套标记所以用上面的方法获取的是“null”

  }

  }

  </script>

  </head>

  <body>

  <h1>一级标题</h1>

  <p>段落</p>

  <h2>二级标题</h2>

  <ul id="eventsList">

  <li>列表项一</li>

  <li>列表项二</li>

  <li><a href="http://www.sina.com">列表项三</a></li>

  <li>列表项四</li>

  </ul>

  <p>段落</p>

  <p>段落</p>

  <input type="button" onclick="myDominspector()" value="Click Me"/>

  </body>

  </html>

  『显示』

  点击按钮后

  LI LI LI LI 列表项一 列表项二 null列表项四 列表项三

  』

  』

  //空白节点

  『

  对于一些文本描述的DOM结构(例如HTML文件),一些浏览器会在元素节点之间插入一些空白节点。

  对于IE,忽略所有空白节点

  『例子』

  『

  /////////外部js脚本:

  addLoadListener(init); //在加载时就运行此脚本

  function init() {

  var star2 = document.getElementById("star1").nextSibling; //得到"star1"的下一个兄弟节点--star2(想的是这样,在IE中能实现,但是在火狐中,会加上相应的空白节点,此处在火狐中获得的是空白节点)

  //alert(star2.nodeName);

  if(star2.nodeType=="3")//3表示文本节点(text_node),空白节点也是文本节点,要是不是空白节点此处的nodeType为1(element_node)

  {

  star2=star2.nextSibling;

  }

  star2.className = "starLink";

  var temp = document.documentElement.firstChild.nextSibling.firstChild; //documentElement表示HTML元素

  alert(temp.nodeName);

  if (temp.nodeType == "3") {

  temp = temp.nextSibling;

  }alert(temp.nodeName);

  return true; //加上这句就是在网页上即使有错误也不会报错,可以继续执行下面的代码

  }

  function addLoadListener(fn) //此函数是验证浏览器的版本是IE还是火狐还是别的什么,可以直接拷贝过来用

  {

  if(typeof window.addEventListener!="undefined")

  {

  window.addEventListener("load",fn,false);

  }

  else if(typeof document.addEventListener!="undefined")

  {

  document.addEventListener("load",fn,false);

  }

  else if(typeof window.attchEvent!="undefined")

  {

  window.attchEvent("load",fn);

  }

  else

  {

  var oldfn=window.onload;

  if(typeof window.onload!="function")

  {

  window.onload=fn;

  }

  else

  {

  window.onload=function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  ----------------------------------------------------

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/BlankNodes.js">

  </script>

  <link rel="Stylesheet" type="text/css" href="css/BlankNoses.css" />

  </head>

  <body>

  <h1>Accessing elements</h1>

  <div id="outerGalaxy">

  <ul id="starList">

  <li id="star1">Rigel</li>

  <li id="star2">Altair</li>

  <li id="star3">Betelgeuse</li>

  </ul>

  </div>

  </body>

  </html>

  』

  』

  //创建元素节点和文本节点 创建方法的选择

  『

  createElements就是创建新元素的函数。

  var newAnchor = document.createElement("a");

  创建函数createTextNode创建文本节点

  var anchorText = document.createTextNode("monoceros");

  有3种基本的方法来将新的元素节点或者文本节点插入到网页中

  放到最后:appendChild ()方法 //用法: 前一个节点.appendChild(后一个节点的名字) 注意:名字不用“”扩起 ; 这种方法是将节点加到“前一个节点”的后面

  放到某节点之前:insertBefore ()方法 //用法 : 父节点.insertBefore(新的节点,已定义好的节点)→→(显示的顺序):新的节点 已定义好的节点

  替换掉原有的某个节点: replaceChild ()方法 //用法 : 父节点.replaceChild(新的节点,旧的节点)→→→(显示结果):新的节点替换掉旧的节点

  『例子』

  『

  下面是外置JS脚本的内容:

  addLoadListener(init);

  function init()

  {

  var anchorText=document.createTextNode("monoceros"); //创建一个文本节点

  var newAnchor = document.createElement("a"); //创建一个元素节点

  newAnchor.href="http://www.baidu.com";//给新建的超链接节点添加链接属性

  newAnchor.appendChild(anchorText); //元素节点和文本节点进行连接

  var parent=document.getElementById("starLinks");

  var newChild=parent.appendChild(newAnchor); //把新建的节点添加到原有超级连接的后面

  return true;

  }

  function addLoadListener(fn) //下面是判断浏览器的类型

  {

  if (typeof window.addEventListener != 'undefined')

  {

  window.addEventListener('load', fn, false);

  }

  else if (typeof document.addEventListener != 'undefined')

  {

  document.addEventListener('load', fn, false);

  }

  else if (typeof window.attachEvent != 'undefined')

  {

  window.attachEvent('onload', fn);

  }

  else

  {

  var oldfn = window.onload;

  if (typeof window.onload != 'function')

  {

  window.onload = fn;

  }

  else

  {

  window.onload = function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  -----------------------------------------------------------

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/CreateElement1.js"></script>

  </head>

  <body>

  <h1>Creating elements and test nodes</h1>

  <p id="starLinks">

  <a href="test1.htm">Sirius</a>

  </p>

  </body>

  </html>

  』

  』

  //改变元素的类型

  『

  没有什么直接的、简单的方法来改变一个元素的类型。

  改变元素类型的主要手段——克隆

  注意:更改DOM的节点结构时要当心

  『例子』

  『

  下面是外置JS脚本的内容:

  addLoadListener(init);

  function init()

  {

  var div=document.createElement("div");

  var p=document.getElementById("starLinks");

  for(var i=0;i<p.childNodes.length;i++)

  {

  var clone=p.childNodes[i].cloneNode(true);//true表示克隆子节点本身

  div.appendChild(clone);

  }

  //debugger;

  div.id=p.getAttribute("id");

  div.className="starLink";

  p.parentNode.replaceChild(div,p);

  }

  function addLoadListener(fn)

  {

  if (typeof window.addEventListener != 'undefined')

  {

  window.addEventListener('load', fn, false);

  }

  else if (typeof document.addEventListener != 'undefined')

  {

  document.addEventListener('load', fn, false);

  }

  else if (typeof window.attachEvent != 'undefined')

  {

  window.attachEvent('onload', fn);

  }

  else

  {

  var oldfn = window.onload;

  if (typeof window.onload != 'function')

  {

  window.onload = fn;

  }

  else

  {

  window.onload = function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  -----------------------------------------------------------

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/ChangeTypeOfElement1.js"></script>

  <link rel="Stylesheet" type="text/css" href="css/BlankNoses.css" />

  </head>

  <body>

  <h1>Changing the type of an element</h1>

  <p id="starLinks">

  <a href="test1.htm">Sirius</a>

  <a href="test2.htm">Achanar</a>

  </p>

  </body>

  </html>

  』

  』

  //删除一个元素或文本节点

  『

  removeChild函数能够用于删除父节点的任意子节点,并返回被删除的对象。

  删除的元素不再存在于DOM中:它只存在于内存中

  『例子1』

  『

  var anchor=document.getElementById("sirius"); //得到要删除的节点对象

  var parent=anchor.parentNode; //找到它的父节点

  var removedChild=parent.removeChild(anchor); //用法 : 父节点.removeChild(子节点对象);

  』

  『例子2』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <link rel="Stylesheet" type="text/css" href="css/BlankNoses.css" />

  <script language="javascript" type="text/javascript" src="javascript/RemoveElement2.js"></script>

  </head>

  <body>

  <h1>Removing an element</h1>

  <div id="starContainer">

  <p id="starLinks" class="starLink">

  <a href="test1.htm">Aldebaran</a>

  <a href="test2.htm">Castor</a>

  </p>

  </div>

  </body>

  </html>

  ----------------------------------------------------------------------------

  下面是外挂式js脚本内容:

  var parent=document.getElementById("starLinks"); //得到父节点的对象(f2)

  var container=document.getElementById("starContainer"); //得到父节点的父节点的对象(f1)

  while(parent.childNodes.length>0)

  {

  container.insertBefore(parent.childNodes[0],parent); //将F2中的子节点和F1对调

  }

  container.removeChild(parent); //对调结束后删除F1

  』

  』

  //读写元素属性

  『

  HTML元素最为常用的部分就是它的属性,JavaScript不仅能够读取这些属性值,而且还能写回新值。

  getAttribute可以用于读取一个属性的值,而setAttribute则可以用于写入新值

  『例子1』

  『

  <a id="antares" href="test1.htm" title="Marssion">Antares</a>

  ---------------------------------------------------------------

  下面是外置JS脚本的内容:

  var anchor=document.getElementById("antares"); //获得要获得属性的那个对象

  var anchorId=anchor.getAttribute("id"); //用法: 获得要获得属性的那个对象.getAttribute("属性名(注意要加“”)")

  var anchorTitle=anchor.getAttribute("title");

  alert("The anchor ID is:"+anchorId+"\nThe anchor title is:"+anchorTitle);

  』

  『例子2』

  『

  <a id="antares" href="test2.htm" title="Marssion">Antares</a>

  ----------------------------------------------------------------

  下面是外置JS脚本的内容:

  var anchor=document.getElementById("antares"); //获得要获得属性的那个对象

  anchor.setAttribute("title","Marssion.lee"); // 用法: 获得要获得属性的那个对象.setAttrubute("属性名(注意要加“”)","要给属性名赋的值(注意要加“”)")

  var newTitle=anchor.getAttribute("title"); //新的属性值会覆盖旧的属性值

  alert("The anchor title is:"+newTitle);

  』

  』

  //获得拥有特定属性值的所有元素

  『

  如果需要在input元素中寻找满足type=“checkbox”这个条件的所有元素

  var inputs = document.getElementsByTagName("input");

  for (var i = 0; i < inputs.length; i++)

  {

  if (inputs.getAttribute("type") == "checkbox")

  {

  ...

  }

  }

  解决方法——getElementsByAttribute函数

  『例子』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/getElementByAttribute.js">

  </script>

  </head>

  <body>

  <h1>Getting all element with a particular attribute value</h1>

  <p id="starLinks">

  <label for="test1">test1</label>

  <a href="test1.htm" title="sirius">Sirius</a>

  <a href="test2.htm" title="marssion">Marssion</a>

  <a href="test2.htm" title="marssion">Marssion</a>

  <a href="test2.htm" title="marssion">Marssion</a>

  <a href="test2.htm" title="marssion">Marssion</a>

  <a href="test2.htm" title="marssion">Marssion</a>

  </p>

  </body>

  </html>

  -------------------------------------------------------------

  下面是外置JS脚本的内容:

  addLoadListener(init)

  function init() {

  var anchors = getElementsByAttribute("title", "marssion"); //取得属性名为"title"属性值为"marssion"的元素集合,此方法在下面定义了拿过来用就行了

  alert("There are " + anchors.length + " elements with the title marssion");

  var label = getElementsByAttribute("for", "test1");

  alert(label.length);

  }

  function getElementsByAttribute(attribute,attributeValue) //这个函数是根据不同的浏览器判断属性和属性值是否符合正则表达式

  {

  var elementArray=new Array();

  var matchedArray=new Array();

  if(document.all)

  {

  elementArray=document.all;//IE获取所有的元素

  }

  else

  {

  elementArray=document.getElementsByTagName("*");//DOM获取所有的元素

  }

  for(var i=0;i<elementArray.length;i++)

  {

  if(attribute=="title")

  {

  var pattern=new RegExp("(^| )"+attributeValue+"( |$)");//实例化正则表达式

  if (pattern.test(elementArray[i].getAttribute(attribute)))//测试是否与表达式匹配

  {

  matchedArray[matchedArray.length]=elementArray[i];

  }

  }

  else if(attribute=="for")

  {

  if(elementArray[i].getAttribute("htmlFor")||elementArray[i].getAttribute("for"))

  {

  if(elementArray[i].htmlFor==attributeValue)

  {

  matchedArray[matchedArray.length]=elementArray[i];

  }

  }

  }

  else if(elementArray[i].getAttribute(attribute)==attributeValue)

  {

  matchedArray[matchedArray.length]=elementArray[i];

  }

  }

  return matchedArray;

  }

  function addLoadListener(fn) //这个函数是判断浏览器的型号

  {

  if (typeof window.addEventListener != 'undefined')

  {

  window.addEventListener('load', fn, false);

  }

  else if (typeof document.addEventListener != 'undefined')

  {

  document.addEventListener('load', fn, false);

  }

  else if (typeof window.attachEvent != 'undefined')

  {

  window.attachEvent('onload', fn);

  }

  else

  {

  var oldfn = window.onload;

  if (typeof window.onload != 'function')

  {

  window.onload = fn;

  }

  else

  {

  window.onload = function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  』

  』

  //元素的class的增减 //class css样式表中的

  『

  元素的class都可以通过className属性访问。

  该属性的值是字符串

  『例子』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <link rel="Stylesheet" type="text/css" href="css/BlankNoses.css" />

  <script language="javascript" type="text/javascript" src="javascript/AddRemoveClasses.js"></script>

  </head>

  <body>

  <h1>Adding and removing multiple classes to/from an element</h1>

  <p>

  <a id="sirius" class="starLink" href="test1.htm">Sirius</a>

  <a id="aldebaran" class="starLink" href="test2.htm">Aldebaran</a>

  </p>

  </body>

  </html>

  -------------------------------------------------------------------------------------------------------------

  下面是外置JS脚本的内容:

  addLoadListener(init);

  function init()

  {

  var sirius=document.getElementById("sirius");

  var aldebaran=document.getElementById("aldebaran");

  addClass(sirius, "important"); //函数在下面都有,拿过来用就行了 两个函数都自动验证正则表达式

  removeClass(aldebaran,"starLink"); //函数在下面都有,拿过来用就行了

  return true;

  }

  function addClass(target,classValue) {

  //debugger;

  var pattern = new RegExp("(^| )" + classValue + "( |$)");

  if(!pattern.test(target.className))

  {

  if(target.className=="")

  {

  target.className=classValue;

  }

  else

  {

  target.className+=" "+classValue; //叠加样式表用空格将两个样式表的名字分开就行了

  }

  }

  return true;

  }

  function removeClass(target,classValue)

  {

  var removedClass = target.className;

  var pattern = new RegExp("(^| )" + classValue + "( |$)");

  if(pattern.test(removedClass))

  {

  target.className="";

  }

  return true;

  }

  function addLoadListener(fn)

  {

  if (typeof window.addEventListener != 'undefined')

  {

  window.addEventListener('load', fn, false);

  }

  else if (typeof document.addEventListener != 'undefined')

  {

  document.addEventListener('load', fn, false);

  }

  else if (typeof window.attachEvent != 'undefined')

  {

  window.attachEvent('onload', fn);

  }

  else

  {

  var oldfn = window.onload;

  if (typeof window.onload != 'function')

  {

  window.onload = fn;

  }

  else

  {

  window.onload = function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  』

  』

  //事件的概念

  『

  JavaScript程序使用的是事件驱动的程序设计模型,某些元素发生了某些事件时,Web浏览器就会生成一个事件(event)

  同一个事件调用多个函数时用";"隔开

  』

  //事件流

  『

  事件流意味着在页面上可以有多个元素响应同一个事件

  分为两类

  『

  1、冒泡型事件(IE) 从最先发生事件的地方一层一层向上返

  2、DOM事件 从最上成(HTML)一层一层向下返

  』

  『

  type

  一个字符串,声明发生的事件的类型,该属性的值是删除前缀“on”的事件处理程序名(如“click”或“mouseover”)

  『例子』

  『

  var sType=oEvent.type;

  function handleEvent(oEvent)

  {

  if(oEvent.type=="click")

  {

  alert("Cilcked!");

  }

  else if(oEvent.type=="mouseover")

  {

  alert("Mouse Over!");

  }

  oDiv.onclick=handleEvent;

  oDiv.onmouseover=handleEvent;

  }

  』

  』

  

复制代码 代码如下:
事件例子

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title></title>

  <script>

  function alert1(fg) {

  document.getElementById("display").innerHTML+=fg+"<br />"

  }

  function checkbtn() {

  switch (event.button) {

  case 1:

  alert1("左键");

  break;

  case 2:

  alert1("右键");

  break;

  case 3:

  alert1("左键+右键");

  break;

  case 4:

  alert1("中间键");

  break;

  case 5:

  alert1("左键+中间键");

  break;

  case 6:

  alert1("右键键+中间键");

  break;

  case 7:

  alert1("左键+中间键+右键");

  break;

  }

  }

  </script>

  </head>

  <body>

  <div onmousedown="checkbtn()" oncontextmenu="return false" style="width:50px;height:50px; background-color:Lime; cursor:hand;">单击</div> //必须用 div 的onmousedown

  <div id="display"></div>

  </body>

  </html>

  』

  

复制代码 代码如下:
事件监听

  IE

  [Object].attachEvent("on+eventName",fnHandler") //eventName :动作的名字 fnHandler :事件函数

  [Object].detachEvent("on+eventName",fnHandler")

  DOM

  [Object].addEventListener("eventName",fnHandler,bCapture)

  [Object].removeEventListener("eventName",fnHandler,bCapture)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml" id="html1">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  var fnClick=function()

  {

  alert("Clicked");

  }

  var fnClick1 = function() {

  alert("body");

  }

  var fnClick2 = function() {

  alert("html");

  }

  var fnLoad = function() {

  var temp = document.getElementById("btn1");

  var temp1 = document.getElementById("body1");

  var temp2 = document.getElementById("html1");

  temp1.addEventListener("click", fnClick1, true);

  temp2.addEventListener("click", fnClick2, true);

  temp.addEventListener("click", fnClick, true); //false用于冒泡阶段 true用于捕获阶段

  }

  var fnDetachEvent=function()

  {

  var temp=document.getElementById("btn1");

  temp.removeEventListener("click",fnClick,true);

  }

  </script>

  </head>

  <body onload="fnLoad()" id="body1">

  <input type="button" id="btn1" value="click me" />

  <input type="button" value="detachEvent" onclick="fnDetachEvent()" />

  </body>

  </html>

  -----------------------------------------------------------------------

  [code]例子2

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  var fnClick=function()

  {

  alert("Clicked");

  }

  var fnLoad=function()

  {

  var temp=document.getElementById("btn1");

  temp.attachEvent("onclick",fnClick);

  }

  var fnDetachEvent=function()

  {

  var temp=document.getElementById("btn1");

  temp.detachEvent("onclick",fnClick);

  }

  </script>

  </head>

  <body onload="fnLoad()">

  <input type="button" id="btn1" value="click me" />

  <input type="button" value="detachEvent" onclick="fnDetachEvent()" />

  </body>

  </html>

  [/code]

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  var EventUtil=new Object;

  EventUtil.addEventHandler=function(oTarget,sEventType,fnHandler){

  if(oTarget.addEventListener)

  {

  oTarget.addEventListener(sEventType,fnHandler,false);

  }

  else if(oTarget.attachEvent)

  {

  oTarget.attachEvent("on"+sEventType,fnHandler);

  }

  else                //要是出现即不是IE又不是火狐的浏览器就执行这条

  {

  oTarget["on"+sEventType]=fnHandler;

  }

  };

  EventUtil.removeEventHandler=function(oTarget,sEventType,fnHandler){

  if(oTarget.removeEventListener)

  {

  oTarget.removeEventListener(sEventType,fnHandler,false);

  }

  else if(oTarget.detachEvent)

  {

  oTarget.detachEvent("on"+sEventType,fnHandler);

  }

  else

  {

  oTarget["on"+sEventType]=null;

  }

  };

  function handleClick()

  {

  alert("Click");

  var oDiv=document.getElementById("div1");

  EventUtil.removeEventHandler(oDiv,"click",handleClick);

  }

  window.onload=function(){

  var oDiv=document.getElementById("div1");

  EventUtil.addEventHandler(oDiv,"click",handleClick);

  }

  </script>

  </head>

  <body>

  <div id="div1" style="background-color:Red; width:100px; height:100px;"></div>

  </body>

  </html>

  //例子(补充)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title></title>

  <script language="javascript" type="text/javascript">

  function load() {

  document.f1.b1.onmouseover = plead; //注意:document点出的是相应的name属性,等号后面调用的函数不用加()

  }

  function plead() {

  window.status = "Please Press Me!";

  }

  </script>

  </head>

  <body onload="load()">

  <form name="f1" action="">

  <input name="b1" type="button" value="Press Me" /> //通过外置事件调用

  </form>

  </body>

  </html>

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function handleEvent(oEvent)

  {

  var oTextbox=document.getElementById("txt1");

  oTextbox.value+="\n>"+oEvent.type; //把事件转换成事件类型进行输出

  }

  </script>

  </head>

  <body>

  <p>Type some characters into the first textbox.</p>

  <p><textarea id="txtInput" rows="15" cols="50"

  onkeydown="handleEvent(event)" onkeyup="handleEvent(event)" onkeypress="handleEvent(event)"></textarea></p> //注意函数传值传的是事件

  <p><textarea id="txt1" rows="15" cols="50"></textarea></p>

  </body>

  </html>

  

复制代码 代码如下:
显示调用事件

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function oldHandle() {

  alert("aa");

  }

  </script>

  </head>

  <body>

  <form name="myForm" action="test1.htm" method="post">

  <input name="myButton" type="button" value="Click Me" onclick="oldHandle()" />

  </form>

  <script language="javascript" type="text/javascript">

  document.myForm.myButton.onclick();//显示调用事件处理程序,但没有引发onclick事件。

  //alert(navigator.userAgent);

  </script>

  </body>

  </html>

  

复制代码 代码如下:
关于事件的返回值

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title></title>

  <script language="javascript" type="text/javascript">

  function check() {

  var textbox = document.getElementById("txt");

  if (textbox.value == "") {

  alert("文本框空了");

  textbox.focus();

  return false;

  }

  else

  {

  return true;

  }

  }

  </script>

  </head>

  <body>

  <form id="form1" onsubmit="return check()"> <!--return 给事件一个boolean返回值,true代表能够继续执行,FALSE代表停止执行(这里的check()相当于一个boll值)-->

  <input type="text" id="txt" /> //onsubmit是提交表单事件

  <input type="submit" value="Submit" />

  <!--<input type="button" onclick="sd()" />-->

  </form>

  </body>

  </html>

  -----------------------------------------------------------------------------

  [code]例子2

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function confirmLink()

  {

  return confirm("Do you really want to visit "+this.href+" ?"); //这是一个有yesno的选项 返回的bool值指示函数是否继续执行

  }

  function confirmAllLinks()

  {

  for(var i=0;i<document.links.length;i++)

  {

  document.links[i].onclick=confirmLink; //动态的将onclick事件进行绑定,如果返回时true就执行链接 返回false就不执行链接

  } //说白了就是

复制代码 代码如下:
事件名=“boolean值(TRUE就执行,FALSE就不执行)”

  }

  </script>

  </head>

  <body onload="confirmAllLinks()">

  <a href="CreateElement1.htm" >点我看看</a>

  <a href="CreateElement1.htm" >点我看看</a>

  <a href="CreateElement1.htm" >点我看看</a>

  <a href="CreateElement1.htm" >点我看看</a>

  <a href="CreateElement1.htm" >点我看看</a>

  <a href="CreateElement1.htm" >点我看看</a>

  </body>

  </html>

  [/code]

  

复制代码 代码如下:
关于加载

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  // document.body.onload=function() //如果取消注释则会出现错误,因为代码是一行一行运行的加载到此处时Body还没有加载,所以用body会出错

  // { //此例子指示解释一下,就算把body换成别的好像也不行,我是没试出来行的

  // alert("Loaded");

  // }

  </script>

  </head>

  <body>

  This example won't work because it's assinging the <code>onload</code> event handler to the wrong place!

  <script language="javascript" type="text/javascript">

  document.body.onload=function() //可以正确执行,因为body已经加载

  {

  alert("Loaded");

  }

  </script>

  </body>

  </html>

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function handleEvent(oEvent)

  {

  var oTextbox=document.getElementById("txt1");

  oTextbox.value+="\n>"+oEvent.type; //见上面关于type的解释

  oTextbox.value+="\n target is "+(oEvent.target||oEvent.srcElement).id;

  oTextbox.value+="\n keyCode is "+oEvent.keyCode; //这是整数属性声明keydown和keyup事件的键代码以及keypress事件的unicode字符,用String.fromCharCode(oEvent.keyCode)方法可以把字符代码转换成字符串

  oTextbox.value+="\n charCode is "+oEvent.charCode;

  var arrKeys=[];

  if(oEvent.shiftKey) //shiftKey ctrlkey altkey 这些bool值属性声明在鼠标事件发生时,是否按住了Alt、Ctrl、Shift键

  {

  arrKeys.push("Shift");

  }

  if(oEvent.ctrlKey)

  {

  arrKeys.push("Ctrl");

  }

  if(oEvent.altKey)

  {

  arrKeys.push("Alt");

  }

  oTextbox.value+="\n keys down are "+arrKeys+" Number is "+arrKeys.length;

  }

  </script>

  </head>

  <body>

  <p>Type some characters into the first textbox.</p>

  <p><textarea id="txtInput" rows="15" cols="50"

  onkeydown="handleEvent(event)" onkeyup="handleEvent(event)" onkeypress="handleEvent(event)"></textarea></p>

  <p><textarea id="txt1" rows="15" cols="50"></textarea></p>

  </body>

  </html>

  』

  『

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title></title>

  <script language="javascript" type="text/javascript" src="javascript/detect.js"></script>

  <script language="javascript" type="text/javascript">

  function load() {

  var textbox = document.getElementById("txt");

  textbox.oncontextmenu = function(oEvent) { //textbox.oncontextmenu 这是控制右键的函数,返回false就禁用右键了

  //debugger;

  if (isIE) { //浏览器要是ie的禁用方法 ,禁用文本框的右键

  oEvent = window.event;

  oEvent.returnValue = false;

  }

  else {

  oEvent.preventDefault();

  }

  }

  document.oncontextmenu = function(oEvent) { //禁用文本框外面的右键

  if (isIE) {

  oEvent = window.event;

  oEvent.returnValue = false;

  }

  else {

  oEvent.preventDefault();

  }

  }

  }

  </script>

  </head>

  <body onload="load()">

  <input value="abcd" id="txt" />

  </body>

  </html>

  -----------------------------------------------------------------------------------------------------

  "javascript/detect.js"脚本中的内容: 这是判断具体的浏览器类型是什么,直接拿过来用就行了

  var sUserAgent = navigator.userAgent;

  var fAppVersion = parseFloat(navigator.appVersion);

  function compareVersions(sVersion1, sVersion2) {

  var aVersion1 = sVersion1.split(".");

  var aVersion2 = sVersion2.split(".");

  if (aVersion1.length > aVersion2.length) {

  for (var i = 0; i < aVersion1.length - aVersion2.length; i++) {

  aVersion2.push("0");

  }

  }

  else if (aVersion1.length < aVersion2.length) {

  for (var i = 0; i < aVersion2.length - aVersion1.length; i++) {

  aVersion1.push("0");

  }

  }

  for (var i = 0; i < aVersion1.length; i++) {

  if (aVersion1[i] < aVersion2[i]) {

  return -1;

  }

  else {

  return 1;

  }

  }

  return 0;

  }

  var isOpera = sUserAgent.indexOf("Opera") > -1;

  var isMinOpera4 = isMinOpera5 = isMinOpera6 = isMinOpera7 = isMinOpera7_5 = false;

  if (isOpera) {

  var fOperaVersion;

  if (navigator.appName == "Opera") {

  fOperaVersion.fAppVersion;

  }

  else {

  var reOperaVersion = new RegExp("Opera (\\d+\\.\\d+)");

  reOperaVersion.test(sUserAgent);

  fOperaVersion = parseFloat(RegExp["$1"]);

  }

  isMinOpera4 = fOperaVersion >= 4;

  isMinOpera5 = fOperaVersion >= 5;

  isMinOpera6 = fOperaVersion >= 6;

  isMinOpera7 = fOperaVersion >= 7;

  isMinOpera7_5 = fOperaVersion >= 7.5;

  }

  var isKHTML = sUserAgent.indexOf("KHTML") > -1 || sUserAgent.indexOf("Konqueror") > -1 || sUserAgent.indexOf("AppleWebKit") > -1;

  var isMinSafari1 = isMinSafari1_2 = false;

  var isMinKonq2_2 = isMinKonq3 = isMinKonq3_1 = isMinKonq3_2 = false;

  if (isKHTML) {

  var isSafari = sUserAgent.indexOf("AppleWebKit") > -1;

  var isKonq = sUserAgent.indexOf("Konqueror") > -1;

  if (isSafari) {

  var reAppleWebKit = new RegExp("AppleWebKit\\/(\\d+(?:\\.\\d*)?)");

  reAppleWebKit.test(sUserAgent);

  var fAppleWebKitVersion = parseFloat(RegExp["$1"]);

  isMinSafari1 = fAppleWebKitVersion >= 85;

  isMinSafari1_2 = fAppleWebKitVersion >= 124;

  }

  else if (isKonq) {

  var reKonq = new RegExp("Konqueror\\/(\\d+(?:\\.\\d+(?:\\.\\d)?)?)");

  reKonq.test(sUserAgent);

  isMinKonq2_2 = compareVersions(RegExp["$1"], "2.2") >= 0;

  isMinKonq3 = compareVersions(RegExp["$1"], "3.0") >= 0;

  isMinKonq3_1 = compareVersions(RegExp["$1"], "3.1") >= 0;

  isMinKonq3_2 = compareVersions(RegExp["$1"], "3.2") >= 0;

  }

  }

  var isIE = sUserAgent.indexOf("compatible") > -1 && sUserAgent.indexOf("MSIE") > -1 && !isOpera;

  var isMinIE4 = isMinIE5 = isMinIE5_5 = isMinIE6 = isMinIE7 = false;

  if (isIE) {

  var reIE = new RegExp("MSIE (\\d+\\.\\d+);");

  reIE.test(sUserAgent);

  var fIEVersion = parseFloat(RegExp["$1"]);

  isMinIE4 = fIEVersion >= 4;

  isMinIE5 = fIEVersion >= 5;

  isMinIE5_5 = fIEVersion >= 5.5;

  isMinIE6 = fIEVersion >= 6.0;

  isMinIE7 = fIEVersion >= 7.0;

  }

  var isMoz = sUserAgent.indexOf("Gecko") > -1 && !isKHTML;

  var isMinMoz1 = sMinMoz1_4 = isMinMoz1_5 = false;

  if (isMoz) {

  var reMoz = new RegExp("rv:(\\d+\\.\\d+(?:\\.\\d+)?)");

  reMoz.test(sUserAgent);

  isMinMoz1 = compareVersions(RegExp["$1"], "1.0") >= 0;

  isMinMoz1_4 = compareVersions(RegExp["$1"], "1.4") >= 0;

  isMinMoz1_5 = compareVersions(RegExp["$1"], "1.5") >= 0;

  }

  var isNS4 = !isIE && !isOpera && !isMoz && !isKHTML

  && (sUserAgent.indexOf("Mozilla") == 0)

  && (navigator.appName == "Netscape")

  && (fAppVersion >= 4.0 && fAppVersion < 5.0);

  var isMinNS4 = isMinNS4_5 = isMinNS4_7 = isMinNS4_8 = false;

  if (isNS4) {

  isMinNS4 = true;

  isMinNS4_5 = fAppVersion >= 4.5;

  isMinNS4_7 = fAppVersion >= 4.7;

  isMinNS4_8 = fAppVersion >= 4.8;

  }

  var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");

  var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC")

  || (navigator.platform == "Macintosh");

  var isUnix = (navigator.platform == "X11") && !isWin && !isMac;

  var isWin95 = isWin98 = isWinNT4 = isWin2K = isWinME = isWinXP = false;

  var isMac68K = isMacPPC = false;

  var isSunOS = isMinSunOS4 = isMinSunOS5 = isMinSunOS5_5 = false;

  if (isWin) {

  isWin95 = sUserAgent.indexOf("Win95") > -1

  || sUserAgent.indexOf("Windows 95") > -1;

  isWin98 = sUserAgent.indexOf("Win98") > -1

  || sUserAgent.indexOf("Windows 98") > -1;

  isWinME = sUserAgent.indexOf("Win 9x 4.90") > -1

  || sUserAgent.indexOf("Windows ME") > -1;

  isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1

  || sUserAgent.indexOf("Windows 2000") > -1;

  isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1

  || sUserAgent.indexOf("Windows XP") > -1;

  isWinNT4 = sUserAgent.indexOf("WinNT") > -1

  || sUserAgent.indexOf("Windows NT") > -1

  || sUserAgent.indexOf("WinNT4.0") > -1

  || sUserAgent.indexOf("Windows NT 4.0") > -1

  && (!isWinME && !isWin2K && !isWinXP);

  }

  if (isMac) {

  isMac68K = sUserAgent.indexOf("Mac_68000") > -1

  || sUserAgent.indexOf("68K") > -1;

  isMacPPC = sUserAgent.indexOf("Mac_PowerPC") > -1

  || sUserAgent.indexOf("PPC") > -1;

  }

  if (isUnix) {

  isSunOS = sUserAgent.indexOf("SunOS") > -1;

  if (isSunOS) {

  var reSunOS = new RegExp("SunOS (\\d+\\.\\d+(?:\\.\\d+)?)");

  reSunOS.test(sUserAgent);

  isMinSunOS4 = compareVersions(RegExp["$1"], "4.0") >= 0;

  isMinSunOS5 = compareVersions(RegExp["$1"], "5.0") >= 0;

  isMinSunOS5_5 = compareVersions(RegExp["$1"], "5.5") >= 0;

  }

  }

  』

  『

  <html xmlns="http://www.w3.org/1999/xhtml" onclick="alert('html')">

  <head>

  <title>无标题页</title>

  <script type="text/javascript" language="javascript" src="javascript/detect.js"></script> //src="javascript/detect.js" 判断浏览器的类型,上面有~

  <script type="text/javascript" language="javascript">

  function handleClick(oEvent) //阻止冒泡

  {

  alert("input");

  if(isIE) {

  oEvent.cancelBubble=true; //ie的阻止冒泡的方法

  }

  else

  {

  oEvent.stopPropagation(); //其他浏览器的阻止冒泡的方法

  }

  }

  </script>

  </head>

  <body onclick="alert('body')">

  <input type="button" value="Click Me" onclick="handleClick(event)" /> //触发onclick事件可弹出三个框,因为按钮包含在他们中间

  </body>

  </html>

  』

  JS 第六章 : 表单和表单元素 ↑↓←→

  //获取Form对象

  

复制代码 代码如下:

  第一种方式:

  document.forms[0]指的就是文档中的第一个表单

  第二种方式:

  通过表单的名称 document.forms[“formZ”];

  第三种方式:

  document.getElementByld(“forml”)

  例子

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title></title>

  <script type="text/javascript" language="javascript">

  function myclick1() {

  var form;

  form = document.forms["samplename"]; //三种获取Form对象的方法

  // form = document.forms[0];

  // form = document.getElementById("myForm");

  alert(form.elements["mytext"].value); //输出文本:Marssion //form.elements["mytext"].value 用于获得表单下的某个元素的值 注意:[]中是用""

  }

  </script>

  </head>

  <body>

  <form id="myForm" name="samplename" action="" method="post"> //method(提交表单的方法(指明浏览器是发送Get请求还是Post请求))[code] 1、Get :不安全,是将信息跟在URL后,最多255个字符

  ↑ 2、post :提交表单时用的方法,安全,放入的字符长度不限

  指向服务器的表单处理程序(一个URL地址,表单提交到的地址) 特殊用法:<!--action="javascript:alert('Submitted')"-->

  <input type="text" value="Marssion" name="mytext"/>

  ↑

  文本框中的默认值

  <input type="button" value="Click Me" onclick="myclick1()"/>

  ↑

  按钮上的文本

  </form>

  </body>

  </html>

  [/code]

  //Form表单提交

  

复制代码 代码如下:

  以前的方法

  <input type="submit" value="提交按钮提交"/>

  采用javascript提交和重置

  submit()和reset()方法

  <input type="button" value="普通按钮提交" onclick="document.forms[0].submit()"/>

  //onsubmit和onreset事件

  

复制代码 代码如下:

  Form对象还提供了事件处理程序onsubmit和onreset

  如果返回false,就取消表单的提交和重置 注意:只有真正点击Submit按钮才会触发onsubmit事件处理程序(给用“type="submit"”)

  例子 onsubmit

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function check() {

  var txtName = document.getElementById("txtName");

  var txtPwd = document.getElementById("txtPassword");

  if (txtName.value == "") {

  alert("请输入用户名");

  txtName.focus();

  return false;

  }

  if (txtPwd.value == "") {

  alert("请输入密码");

  txtPwd.focus();

  return false;

  }

  return true;

  }

  </script>

  </head>

  <body>

  <form id="form1" method="post" action="Handler.ashx" onsubmit="return check()"> <!-- 注意: 在 form中写入 onsubmit="return 函数名()"-->

  <label for="txtName">Name:</label><br />

  <input type="text" id="txtName" name="txtName" /><br />

  <label for="txtPassword">Password:</label><br />

  <input type="password" id="txtPassword" name="txtPassword" /><br />

  <label for="selAge">Age:</label><br />

  <select name="selAge" id="selAge">

  <option>18-21</option>

  <option>22-25</option>

  <option>26-29</option>

  <option>30-35</option>

  <option>Over 35</option>

  </select><br />

  <label for="txtComments">Comments:</label><br />

  <textarea rows="10" cols="50" id="txtComments" name="txtComments"></textarea><br />

  <input type="submit" value="提交按钮提交"/> <!--提交按钮会触发onsubmit事件-->

  <input type="button" value="普通按钮提交" onclick="document.forms[0].submit()" /> <!--普通按钮可以成功提交,但是不能触发onsubmit事件-->

  </form>

  <p>This example blocks the form submissiong(you won't see an alert box).</p>

  </body>

  </html>

  例子onreset

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  </head>

  <body>

  <form method="post" action="javascript:alert('Submitted')" onreset="return confirm('Really erase All data and start over?')">

  <p>Type some values into the textboxes and then press reset.</p>

  <label for="txtName">Name:</label><br />

  <input type="text" id="txtName" name="txtName" /><br />

  <label for="txtPassword">Password</label><br />

  <input type="password" id="txtPassword" name="txtPassword" /><br />

  <label for="selAge">Age:</label><br />

  <select name="selAge" id="selAge">

  <option>18-21</option>

  <option>22-25</option>

  <option>26-29</option>

  <option>30-35</option>

  <option>Over 35</option>

  </select><br />

  <label for="txtComments">Comments:</label><br />

  <textarea rows="10" cols="50" id="txtComments" name="txtComments"></textarea><br />

  <input type="submit" value="Submit Form" />

  <input type="reset" value="重置按钮" /> <!--和onsubmit不同不管是"type="reset"重置按钮" 还是“onclick="document.forms[0].reset()"”都能成功调用onreset事件-->

  <input type="button" value="普通按钮" onclick="document.forms[0].reset()" />

  </form>

  </body>

  </html>

  //保证表单提交一次

  

复制代码 代码如下:

  解决方法:使用一般按钮,添加如下事件:

  <input type=”button” value=”Submit”

  onclick=”this.disabled=true; this.form.submit()” />

  例子

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function sub(){

  setTimeout("sub1()",3000); <!--<script></script>中写的两个函数是模拟网速慢的情况下延时提交的情况-->

  }

  function sub1(){

  document.forms[0].submit();

  }

  </script>

  </head>

  <body>

  <form method="post" action="../Default.aspx" name="form1">

  <input type="text" name="txtName" value="" />

  <input type="button" value="Submit Form" name="mySubmit1" onclick="mySubmit1.disabled=true;sub();" />

  </form>

  </body>

  </html>

  //表单和表单元素的name

  

复制代码 代码如下:

  可以使用下面的表达式引用“address”的表单中的“zipcode”元素,表单和元素都要使用name属性

  document.address.zipcode

  比使用硬编码(位置依赖)的数组下标要简洁得多:

  document.forms[1].elements[4]

  例子

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title></title>

  <script language="javascript" type="text/javascript">

  function showTextBoxValue() {

  //debugger

  alert(document.forms[0].elements[1].value);

  alert(document.myForm.txt.value); //打印出的是文本框中填入的值 注意!:document后面的都是元素的name!,而且不能点出只能硬打

  }

  </script>

  </head>

  <body>

  <form id="form1" method="post" action="#" name="myForm">

  <input type="text" id="txtName" name="txt" />

  <input type="button" id="btnSubmit" value="ShowValue" onclick="showTextBoxValue()" />

  </form>

  </body>

  </html>

  //表单元素通用方法和属性

  

复制代码 代码如下:

  Type:一个只读字符串,标识表单元素的类型。

  Form:对包含该元素的form对象的只读引用 //就是表单A的一个元素B B.From=A

  Name:由HTML的name性质指定的只读字符串。

  Value:一个可读写的字符串,指定了表单元素包含或表示的“值”。

  方法:blur()和focus()

  例子(blur)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  </head>

  <body>

  <p>Type a few characters in the textbox and then tab to the Submit button.

  Then,click on the textbox and tab back to the Submit button without changing the text.

  </p>

  <form method="post" action="javascript:alert('Submited')"> <!--当按下提交按钮时发生的动作-->

  <input type="text" name="textbox" value="" onblur="alert('Blur')" onchange="alert('Change')" /> <!--失去焦点时发生onblur事件 文本框中的内容发生改变当失去焦点时发生onchange事件-->

  <input type="submit" value="Submit Form" />

  </form>

  </body>

  </html>

  //常见的表单元素支持的事件处理程序

  

复制代码 代码如下:

  Onclick:当用户在元素上点击鼠标时触发。

  Onchange:当用户改变了元素表示的值(通过输入文本或选择一个选项)时触发。

  Onfocus:在表单元素收到输入焦点是触发

  Onblur:在表单元素失去输入焦点时触发

  //文本框对象

  

复制代码 代码如下:

  事件:

  {

  onBlur 文本框失去焦点

  onChange 文本框的值被修改(事件将跟踪用户在文本框中所作的修改,当用户在文本框中完成修改之后,将激活该事件。)

  onFocus 光标进入文本框中

  }

  方法:

  {

  select( ) 选中文本内容,突出显示输入区域(选中文本内容,突出显示输入区域,一般用于提示用户重新输入。(全部选中,就像QQ的输入用户名时一双击就将文本框中的内容全部选中,一点删除就全部删除))

  }

  属性:

  {

  value 表示用户输入的文本。

  Size 规定文本可见长度

  Maxlength 规定可输入最大长度

  readonly 某些文本框希望用户不能修改,例如,某个拍卖网站的起拍价,一般是卖方或拍卖公司定价,所以希望用户不能修改,这时可以指定readonly只读属性

  }

  例子(文本框对象 onChange事件)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function getLength()

  {

  var oTextbox1=document.getElementById("txt1");

  var oTextbox2=document.getElementById("txt2");

  alert("The length of txt1 is " + oTextbox1.value.length + "\n" //oTextbox1.value.length属性是获得文本框中文本的长度

  +"The length of txt2 is "+oTextbox2.value.length);

  }

  function change(){

  document.getElementById("loading").src="img/loading_32x32.gif"; //指定图片的路径

  document.getElementById("loading").style.display = "block"; //style.display="block" 含义是让图片显示出来

  }

  function f(){

  document.getElementById("loading").src="img/16checkcircle.gif"; //改变

  }

  </script>

  </head>

  <body>

  <table cellpadding="0" cellspacing="0">

  <tr>

  <td><input type="text" size="12" id="txt1" onchange="change();" /></td> <!--当用户点击别的地方,焦点离开此文本框的时候,将触发onchange事件-->

  <td><img id="loading" width="17" height="17" style="display:none" alt="" /></td> <!--style="display:none" 含义是让图片隐藏-->

  </tr>

  </table>

  <textarea rows="5" cols="25" id="txt2" onkeypress="f()"></textarea><br /> <!--onkeypress事件是当用户在多行文本框中键入值是触发此事件-->

  <input type="button" value="Get Length" onclick="getLength()" />

  </body>

  </html>

  例子(文本框的文本属性,(动态添加子节点))

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function getValues()

  {

  var oTextbox1=document.getElementById("txt1");

  var oTextbox2=document.getElementById("txt2");

  var resultDiv=document.getElementById("result");

  var childNode=document.createTextNode(""); //建立一个空的文本节点

  childNode.nodeValue=oTextbox1.value+oTextbox2.value;

  if(resultDiv.childNodes.length==0) //如果层(父节点)的子节点的个数等于0

  {

  resultDiv.appendChild(childNode);

  }

  else

  {

  resultDiv.removeChild(resultDiv.childNodes[0]); //如果层(父节点)的子节点的个数不等于0 ,先删除第一个子节点,在加入新的子节点

  resultDiv.appendChild(childNode);

  }

  }

  </script>

  </head>

  <body>

  <input type="text" size="12" id="txt1" /><br />

  <textarea rows="5" cols="25" id="txt2"></textarea>

  <input type="button" value="Get Values" onclick="getValues()" /><br />

  <div id="result"></div>

  </body>

  </html>

  例子(select方法)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function selectText()

  {

  var oTextbox1=document.getElementById("txt1");

  oTextbox1.select(); //select()方法 :将相应的文本框中的内容全部选中

  }

  </script>

  </head>

  <body>

  <input type="text" size="12" id="txt1" value="initial value" onselect="alert('Selected')" /><br /> <!--onselect事件:当用户选定文本时发生(不管选定多长)-->

  <input type="button" value="Select Text" onclick="selectText()" />

  </body>

  </html>

  //下拉列表框(List Boxes and Combo Boxes )

  

复制代码 代码如下:

  属性:

  value 属性表示该控件当前选定的值。

  size属性表示可以显示的项目数。

  options集合

  例子(ListboxSelectedIndex)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function showSelectedIndex()

  {

  var oListbox=document.getElementById("selListbox");

  alert(oListbox.selectedIndex); //oListbox.selectedIndex 显示的是listbox(listbox中的选项成一个数组)选中的那一项在数组中的索引号(没选中则显示-1)

  }

  </script>

  </head>

  <body>

  <form action="#" method="post">

  <select id="selListbox" size="2"> <!--<select>中的size属性指示的是用户能看见的选项数目-->

  <option>Original Value0</option>

  <option>Original Value1</option>

  <option>Original Value2</option>

  <option>Original Value3</option>

  <option>Original Value4</option>

  </select><br />

  Select an option in the listbox and click "Show Selected Index".<br />

  <input type="button" value="Show Selected Index" onclick="showSelectedIndex()" />

  </form>

  </body>

  </html>

  例子添加options

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/listutil.js"></script> //外置JS脚本下面有

  <script language="javascript" type="text/javascript">

  function addItem()

  {

  var oListbox=document.getElementById("selListbox");

  var oTxtName=document.getElementById("txtName");

  var oTxtValue=document.getElementById("txtValue");

  ListUtil.add(oListbox,oTxtName.value,oTxtValue.value);

  }

  </script>

  </head>

  <body>

  <form action="#">

  <select id="selListbox" size="1">

  <option>Original Value</option>

  </select><br />

  Click the Add button to add item with the following information:<br />

  Name:<input type="text" id="txtName" /><br />

  Value:<input type="text" id="txtValue" /><br />

  <input type="button" value="Add" onclick="addItem()" />

  </form>

  </body>

  </html>

  例子(一键式为所有超级链接添加onclick事件,跨窗体传递超链接内容)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  function confirmclick()

  {

  return confirm("Do you really want to visit"+location.href+"?");

  }

  function confirmAllLinks()

  {

  for(var i=0;i<document.links.length;i++) //document.links 为此项目的所有超级链接

  {

  document.links[i].onclick=confirmclick; //为所有的超级链接添加onclick事件

  }

  }

  // window.onload=confirmAllLinks; //在窗体加载时就直接执行该函数

  function listlinks(d)

  {

  var newwin=window.open("","linklist","menubar,scrollbars,resizable,width=600,height=300");

  for(var i=0;i<d.links.length;i++)

  {

  newwin.document.write('<a href="'+d.links[i].href+'">'); //注意<a 中的格式‘'

  newwin.document.write(d.links[i].href);

  newwin.document.writeln("</a><br />");

  }

  }

  </script>

  </head>

  <body>

  <input type="button" onclick="alert(typeof this.onclick)" value="click me" />

  <input type="button" value="Click Here" onclick="if(window.numclicks)numclicks++;else numclicks=1;this.value='Click #'+numclicks;" />

  <a href="../js07/test1.htm">mattlee</a>

  <a href="../js07/test2.htm">marssion</a>

  <input type="button" value="link event" onclick="confirmAllLinks()" />

  <input type="button" value="link event" onclick="listlinks(document)" />

  </body>

  </html>

  例子(在文本框中只能输入数字键)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script type="text/javascript" language="javascript" src="javascript/detect.js"></script> //验证浏览器的内容,在jS第五章中有

  <script type="text/javascript" language="javascript" src="javascript/eventutil.js"></script>

  <script type="text/javascript" language="javascript" src="javascript/textutil.js"></script>

  </head>

  <body>

  <p>Try typing in the textbox. You can only type number characters.</p>

  <!--要在keypress事件处理函数中调用这个方法,当字符被允许时返回true,不允许时返回false-->

  <form method="post" action="javascript:alert('submitted')">

  <textarea rows="10" cols="25" validchars="0123456789d" onkeypress="return TextUtil.allowChars(this,event,false)"></textarea>

  <input type="submit" value="Submit Form" /> <!--↑-->

  </form> <!--this:返回<textarea>对象本身; event:系统自动生成的事件直接打上去就行,boolean值:true:屏蔽ctrl+v false:可以用ctrl+v

  这种阻止复制粘贴的方法只适用于火狐,在IE中用“onpaste="return false"”加在<>中就可以了-->

  </body>

  </html>

  --------------------------------------------------------------------------------------------------------------------------------------------

  src="javascript/textutil.js"中的内容:

  var TextUtil=new Object();

  TextUtil.isNotMax=function(oTextArea)//判断文本框内的内容的长度是否于文本框的最大长度相等

  {

  return oTextArea.value.length!=oTextArea.getAttribute("maxlength");

  };

  TextUtil.blockChars = function(oTextbox, oEvent, bBlockPaste)//阻止数字字符

  {

  oEvent = EventUtil.formatEvent(oEvent); //格式化事件

  var sInvalidChars = oTextbox.getAttribute("invalidchars"); //获取元素的validchars属性值,相当于验证字符串

  var sChar = String.fromCharCode(oEvent.charCode); //获取键盘录入的数据

  var bIsValidChar = sInvalidChars.indexOf(sChar) == -1; //录入的数据不包含在验证字符串中返回true

  if (bBlockPaste) {

  return bIsValidChar && !(oEvent.ctrlKey && sChar == "v"); //不支持IE,IE通过onpaste事件控制

  }

  else {

  return bIsValidChar || oEvent.ctrlKey;

  }

  };

  TextUtil.allowChars = function(oTextbox, oEvent, bBlockPaste)//允许数字字符

  {

  oEvent = EventUtil.formatEvent(oEvent); //格式化事件

  var sValidChars = oTextbox.getAttribute("validchars"); //获取元素的validchars属性值,相当于验证字符串

  var sChar = String.fromCharCode(oEvent.charCode); //获取键盘录入的数据

  var bIsValidChar = sValidChars.indexOf(sChar) > -1; //录入的数据包含在验证字符串中返回true

  if (bBlockPaste) {

  return bIsValidChar && !(oEvent.ctrlKey && sChar == "v"); //阻止粘贴快捷键ctrl+v

  }

  else {

  return bIsValidChar || oEvent.ctrlKey;

  }

  };

  TextUtil.blurBlock = function(oTextbox) {

  var sInvalidChars = oTextbox.getAttribute("invalidchars"); //获取元素的validchars属性值,相当于验证字符串

  var arrInvalidChars = sInvalidChars.split("");//将验证字符串分隔为字符数组

  for (var i = 0; i < arrInvalidChars.length; i++) {

  if (oTextbox.value.indexOf(arrInvalidChars[i]) > -1) {//如果文本框的值包含数组中的任意字符,则验证不通过

  alert("Character'" + arrInvalidChars[i] + "' not allowed.");

  oTextbox.focus();

  oTextbox.select();

  return;

  }

  }

  };

  TextUtil.blurAllow=function(oTextbox)

  {

  var sValidChars=oTextbox.getAttribute("validchars");

  var arrTextChars=oTextbox.value.split("");

  for(var i=0;i<arrTextChars.length;i++)

  {

  if(sValidChars.indexOf(arrTextChars[i])==-1)

  {

  alert("Character '"+arrTextChars[i]+"' not allowed.");

  }

  }

  };

  TextUtil.numericScroll=function(oTextbox,oEvent)

  {

  oEvent=EventUtil.formatEvent(oEvent);

  var iValue=oTextbox.value.length==0?0:parseInt(oTextbox.value);//获取文本框中的值,如果没填采用默认值0

  var iMax=oTextbox.getAttribute("max");//获取最大值

  var iMin=oTextbox.getAttribute("min");//获取最小值

  if(oEvent.keyCode==38)//上箭头

  {

  if(iMax==null || iValue<iMax)

  {

  oTextbox.value=(iValue+1);

  }

  }

  else if(oEvent.keyCode==40)//下箭头

  {

  if(iMin==null || iValue>iMin)

  {

  oTextbox.value=(iValue-1);

  }

  }

  };

  TextUtil.autosuggestMatch=function(sText,arrValues)

  {

  var arrResult=new Array();

  if(sText!="")

  {

  for(var i=0;i<arrValues.length;i++)

  {

  if(arrValues[i].indexOf(sText)==0)//在数组中查找是否包含传入字符,如果匹配将该数组元素存入新数组

  {

  arrResult.push(arrValues[i]);

  }

  }

  }

  return arrResult;

  };

  TextUtil.autosuggest=function(oTextbox,arrValues,sListboxId)

  {

  var oListbox=document.getElementById(sListboxId);//通过传入ID 获取指定列表框

  var arrMatches=TextUtil.autosuggestMatch(oTextbox.value,arrValues);

  ListUtil.clear(oListbox);//清空列表框

  for(var i=0;i<arrMatches.length;i++)

  {

  ListUtil.add(oListbox,arrMatches[i]);//将匹配的值填入列表框

  }

  };

  --------------------------------------------------------------------------------------------------------------------------

  src="javascript/eventutil.js"中的内容:

  var EventUtil=new Object;

  EventUtil.addEventHandler=function(oTarget,sEventType,fnHandler){

  if(oTarget.addEventListener)

  {

  oTarget.addEventListener(sEventType,fnHandler,false);

  }

  else if(oTarget.attachEvent)

  {

  oTarget.attachEvent("on"+sEventType,fnHandler);

  }

  else

  {

  oTarget["on"+sEventType]=fnHandler;

  }

  };

  EventUtil.removeEventHandler=function(oTarget,sEventType,fnHandler){

  if(oTarget.removeEventHandler)

  {

  oTarget.removeEventHandler(sEventType,fnHandler,false);

  }

  else if(oTarget.detachEvent)

  {

  oTarget.detachEvent("on"+sEventType,fnHandler);

  }

  else

  {

  oTarget["on"+sEventType]=null;

  }

  };

  //通过格式化事件函数,尽量将IE标准向DOM标准靠拢

  EventUtil.formatEvent=function(oEvent){

  if(isIE && isWin)

  {

  oEvent.charCode=(oEvent.type=="keypress")?oEvent.keyCode:0;//DOM有charCode IE有keyCode 使用这样的方式使IE兼容DOM

  //eventPhase 属性返回事件传播的当前阶段。它的值是Event.CAPTURING_PHASE(1) Event.AT_TARGET(2) Event.BUBBLING_PHASE(3)三个常量之一,它们分别表示捕获阶段、正常事件派发和起泡阶段。

  oEvent.eventPhase=2;

  oEvent.isChar=(oEvent.charCode>0);

  oEvent.pageX=oEvent.clientX+document.body.scrollLeft;

  oEvent.pageY=oEvent.clientY+document.body.scrollTop;

  oEvent.preventDefault=function(){//取消事件的默认动作。

  this.returnValue=false;

  };

  if(oEvent.type=="mouseout")

  {

  oEvent.relatedTarget=oEvent.toElement;

  }

  else if(oEvent.type=="mouseover")

  {

  oEvent.relatedTarget=oEvent.fromElement;

  }

  oEvent.stopPropagation=function(){

  this.cancelBubble=true;

  };

  oEvent.target=oEvent.srcElement;

  oEvent.time=(new Date).getTime();

  };

  return oEvent;

  };

  EventUtil.getEvent=function(){

  if(window.event)

  {

  return this.formatEvent(window.event);

  }

  else

  {

  return EventUtil.getEvent.caller.arguments[0];

  }

  };

  例子(自动查找,就像手机中的通讯录)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/listutil.js"></script>

  <script language="javascript" type="text/javascript" src="javascript/textutil.js"></script> //上面有

  <script language="javascript" type="text/javascript">

  var arrColors=["red", "orange", "yellow", "green", "blue", "indigo",

  "violet", "brown", "black", "tan", "ivory", "navy",

  "aqua", "white", "purple", "pink", "gray", "silver"];

  arrColors.sort(); //对上述数组进行排序

  function setText(oListbox,sTextboxID)

  {

  var oTextbox=document.getElementById(sTextboxID);

  if(oListbox.selectedIndex>-1)

  {

  oTextbox.value=oListbox.options[oListbox.selectedIndex].text; //options:下拉列表框中的元素的集合,通过元素的索引号进行访问

  }

  }

  </script>

  </head>

  <body>

  <p>Type in a color in lowercase:</p>

  <input type="text" id="txtColor" onkeyup="TextUtil.autosuggest(this,arrColors,'lstColors')" /><br /><br />

  <!-- ↑

  this:将文本框自己传过去;arrColors:将要从中查找的总数组传过去;'lstColors'(注意加‘'传入对象的id名时加‘'

  为的是不将传入得东西当成一个对象而是仅仅当成一个字符串,为后面在函数中用此字符串当id号找对象做准备)将要查出的文本的现实地点传过去-->

  <select id="lstColors" size="5" style="width:200px" onclick="setText(this,'txtColor')"></select>

  </body>

  </html>

  -------------------------------------------------------------------------------------------------------------------------------------

  src="javascript/listutil.js"中的内容:

  var ListUtil=new Object();

  ListUtil.getSelectedIndexes=function(oListbox)

  {

  var arrIndexes=new Array();

  for(var i=0;i<oListbox.options.length;i++)

  {

  if(oListbox.options[i].selected)//获取选中项的索引

  {

  arrIndexes.push(i);

  }

  }

  return arrIndexes;

  };

  ListUtil.add=function(oListbox,sName,sValue)

  {

  var oOption=document.createElement("option");

  oOption.appendChild(document.createTextNode(sName));

  if(arguments.length==3)//如果传入了第三个参数,则添加属性

  {

  oOption.setAttribute("value",sValue);

  }

  oListbox.appendChild(oOption);

  };

  ListUtil.remove=function(oListbox,iIndex)//通过索引删除项

  {

  oListbox.remove(iIndex); //oListbox.remove硬打上去的

  };

  ListUtil.clear=function(oListbox)//清空列表框

  {

  for(var i=oListbox.options.length-1;i>=0;i--) {

  ListUtil.remove(oListbox,i);

  }

  };

  ListUtil.move=function(oListboxFrom,oListboxTo,index)

  {

  var oOption=oListboxFrom.options[index];

  if(oOption!=null)

  {

  oListboxTo.appendChild(oOption);//元素节点同时只能属于一个父节点,所以实现了移动

  }

  };

  ListUtil.copy=function(oListboxFrom,oListboxTo,index)

  {

  var oOption=oListboxFrom.options[index];//获取原节点元素,并且创建新的元素几点,从原节点取值

  var newOption=document.createElement("option");

  var newTxtNode=document.createTextNode(oOption.firstChild.nodeValue);

  newOption.appendChild(newTxtNode);

  if(newOption!=null)

  {

  oListboxTo.appendChild(newOption);

  }

  }

  ListUtil.shiftUp=function(oListbox,index)//选项向上移动

  {

  if(index>0)

  {

  var oOption=oListbox.options[index];//获取当前项

  var oPrevOption=oListbox.options[index-1];//获取上一项

  oListbox.insertBefore(oOption,oPrevOption);

  }

  };

  ListUtil.shiftDown=function(oListbox,index)

  {

  if(index<oListbox.options.length-1)

  {

  var oOption = oListbox.options[index]; //获取当前项

  var oNextOption=oListbox.options[index+1];//获取下一项

  oListbox.insertBefore(oNextOption,oOption);

  }

  };

  例子(禁止输入数字)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/detect.js"></script> // 脚本上面都有Copy下来看

  <script language="javascript" type="text/javascript" src="javascript/eventutil.js"></script>

  <script language="javascript" type="text/javascript" src="javascript/textutil.js"></script>

  </head>

  <body>

  <p>Try typing in the textbox.You can only type non-number characters.</p>

  <form method="post" action="javascript:alert('submitted')">

  <textarea rows="10" cols="25" invalidchars="0123456789" onkeypress="return TextUtil.blockChars(this,event,true)"></textarea>

  <input type="submit" value="Submit Form" />

  </form>

  </body>

  </html>

  例子(一个复杂的例子,关于可以将已经选定的文本框和单选按钮的值总结并显示出来)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript">

  var radCPUSpeedIndex=0;

  function radCPUSpeed_onclick(radIndex)

  {

  var returnValue=true;

  if(radIndex==1)

  {

  returnValue=false;

  alert("Sorry that processor speed is currently unavailible");

  document.forms[0].radCPUSpeed[radCPUSpeedIndex].checked=true;

  }

  else

  {

  radCPUSpeedIndex=radIndex;

  }

  return returnValue;

  }

  function butCheck_onclick()

  {

  var controlIndex;

  var element;//debugger

  var numberOfControls=document.forms[0].length; //document.forms[0]表示的是第一张表单中命了名的元素的集合

  var compSpec="Your chosen processor speed is ";

  compSpec=compSpec+document.forms[0].radCPUSpeed[radCPUSpeedIndex].value; //forms[0].radCPUSpeed[radCPUSpeedIndex] 在上一个函数(在选择单选按钮时已经触发)已经将选定的数组索引赋值了

  compSpec=compSpec+"\nWith the following additional components\n";

  for(controlIndex=0;controlIndex<numberOfControls;controlIndex++)

  {

  element=document.forms[0][controlIndex];

  if(element.type=="checkbox")

  {

  if(element.checked==true)

  {

  compSpec=compSpec+element.value+"\n";

  }

  }

  }

  alert(compSpec);

  }

  </script>

  </head>

  <body>

  <form action="javascript:alert('Submit')" method="post">

  <p>Tick all of the components you want included on your coumputer</p>

  <table border="1">

  <tr>

  <td>DVD-RW</td>

  <td><input type="checkbox" name="chkDVD" value="DVD-RW" /></td>

  </tr>

  <tr>

  <td>CD-ROM</td>

  <td><input type="checkbox" name="chkCD" value="CD-ROM" /></td>

  </tr>

  <tr>

  <td>Zip Drive</td>

  <td><input type="checkbox" name="chkZip" value="ZIP Drive" /></td>

  </tr>

  </table>

  <p>Select the processor speed you require</p>

  <table border="1">

  <tr>

  <td><input type="radio" name="radCPUSpeed" checked="checked" onclick="return radCPUSpeed_onclick(0)" value="3.8 Ghz" /></td>

  <td>3.8 Ghz MHz</td>

  <td><input type="radio" name="radCPUSpeed" onclick="return radCPUSpeed_onclick(1)" value="4.8 Ghz" /></td>

  <td>4.8 Ghz MHz</td>

  <td><input type="radio" name="radCPUSpeed" onclick="return radCPUSpeed_onclick(2)" value="6 Ghz" /></td>

  <td>6 Ghz MHz</td>

  </tr>

  </table>

  <input type="button" value="Check Form" name="butCheck" onclick="return butCheck_onclick()" />

  </form>

  </body>

  </html>

  例子(不同父节点之间的子节点的移动和删除)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/listutil.js"></script> //脚本上面有

  <script language="javascript" type="text/javascript">

  function moveItem()

  {

  var oListbox1=document.getElementById("selListbox1");

  var oListbox2=document.getElementById("selListbox2");

  var oTxtIndex=document.getElementById("txtIndex");

  ListUtil.move(oListbox1,oListbox2,parseInt(oTxtIndex.value)); //

  }

  function copyItem()

  {

  var oListbox1=document.getElementById("selListbox1");

  var oListbox2=document.getElementById("selListbox2");

  var oTxtIndex=document.getElementById("txtIndex");

  ListUtil.copy(oListbox1,oListbox2,parseInt(oTxtIndex.value));

  }

  </script>

  </head>

  <body>

  <form action="#" method="post">

  <select id="selListbox1" size="5">

  <option>Original Value 1-0</option>

  <option>Original Value 1-1</option>

  <option>Original Value 1-2</option>

  <option>Original Value 1-3</option>

  <option>Original Value 1-4</option>

  </select>

  <select id="selListbox2" size="5">

  <option>Original Value 2-0</option>

  <option>Original Value 2-1</option>

  <option>Original Value 2-2</option>

  <option>Original Value 2-3</option>

  <option>Original Value 2-4</option>

  </select>

  <p>Clice the Move button to move the item with this position:</p>

  <input type="text" id="txtIndex" /><br />

  <input type="button" value="Move" onclick="moveItem()" />

  <input type="button" value="Copy" onclick="copyItem()" />

  </form>

  </body>

  </html>

  例子(限制多行文本框的输入最大值)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/textutil.js"></script>

  </head>

  <body>

  <p>Try typing in the textbox. You can only type 25 characters.</p>

  <form method="post" action="javascript:alert('Submitted')">

  <textarea rows="10" cols="20" maxlength="25" onkeypress="return TextUtil.isNotMax(this)"></textarea>

  <input type="submit" value="Submit Form" />

  </form>

  </body>

  </html>

  --------------------------------------------------------------------------

  外置脚本中的调用的方法:

  TextUtil.isNotMax=function(oTextArea)//判断文本框内的内容的长度是否于文本框的最大长度相等

  {

  return oTextArea.value.length!=oTextArea.getAttribute("maxlength");

  };

  例子(三个文本框,输入达到第一个文本框的最大值,光标自动移到下一个文本框...)

  

复制代码 代码如下:

  html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script type="text/javascript" language="javascript" src="javascript/formutil.js"></script>

  </head>

  <body>

  <p>Enter your phone number below (ZH style ##-####-######):</p>

  <form method="post" action="javascript:alert('submit')">

  <input type="text" size="2" maxlength="2" value="" onkeyup="FormUtil.tabForward(this)" />

  <input type="text" size="4" maxlength="4" value="" onkeyup="FormUtil.tabForward(this)" />

  <input type="text" size="7" maxlength="7" value="" onkeyup="FormUtil.tabForward(this)" />

  <input type="submit" value="Submit Form" />

  </form>

  </body>

  </html>

  -------------------------------------------------------------------------------------

  src="javascript/formutil.js"中的文本:

  var FormUtil=new Object;

  FormUtil.focusOnFirst = function() {

  if (document.forms.length > 0) {//通过form的length属性判断表单中是否有其他元素

  for (var i = 0; i < document.forms[0].elements.length; i++) {

  var oField = document.forms[0].elements[i];

  if (oField.type != "hidden") {

  if (oField.value == "") {//在页面载入很慢的情况下,该脚本可能还没有运行,用户就已经输入了数据,当执行到该脚本的时候,会给用户带来不便。

  oField.focus();

  return;

  }

  }

  }

  }

  };

  FormUtil.setTextboxes=function()

  {

  var colInputs=document.getElementByTagName("input");

  var colTextAreas=document.getElementsByTagName("textarea");

  for(var i=0;i<colInputs.length;i++)

  {

  if(colInputs[i].type=="text" || colInputs[i].type=="password")

  {

  colInputsp[i].onfocus=function(){this.select();};

  }

  }

  for(var i=0;i<colTextAreas.length;i++)

  {

  colTextAreas[i].onfocus=function(){this.select();};

  }

  };

  FormUtil.tabForward = function(oTextbox) {

  var oForm = oTextbox.form;

  //条件为最后一个元素不是文本框并且文本框值的长度和文本框最大长度相等时

  if (oForm.elements[oForm.elements.length - 1] != oTextbox && oTextbox.value.length == oTextbox.maxLength) { //oForm.elements[oForm.elements.length - 1] != oTextbox判断当前传进来的文本框不是最后一个文本框

  for (var i = 0; i < oForm.elements.length; i++) { //oTextbox.value.length == oTextbox.maxLength 判断当前输入的文本有没有达到它的最大值

  if (oForm.elements[i] == oTextbox) {

  if (oForm.elements[i + 1].type != "hidden") {

  oForm.elements[i + 1].focus();

  return;

  }

  return;

  }

  }

  }

  };

  例子(当焦点离开时验证文本框中的内容)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/detect.js"></script>

  <script language="javascript" type="text/javascript" src="javascript/eventutil.js"></script>

  <script language="javascript" type="text/javascript" src="javascript/textutil.js"></script>

  </head>

  <body>

  <p>Type a number into the textbox,then press the up or down arrow.</p>

  <form method="post" action="javascript:alert('submit')">

  <input type="text" onkeypress="return TextUtil.allowChars(this,event)" max="20" min="-10" validchars="0123456789" onblur="TextUtil.blurAllow(this)"

  onkeydown="TextUtil.numericScroll(this,event)" />

  <input type="button" value="Submit Form" />

  </form>

  </body>

  </html>

  --------------------------------

  js:

  TextUtil.blurBlock = function(oTextbox) {

  var sInvalidChars = oTextbox.getAttribute("invalidchars"); //获取元素的validchars属性值,相当于验证字符串

  var arrInvalidChars = sInvalidChars.split("");//将验证字符串分隔为字符数组

  for (var i = 0; i < arrInvalidChars.length; i++) {

  if (oTextbox.value.indexOf(arrInvalidChars[i]) > -1) {//如果文本框的值包含数组中的任意字符,则验证不通过

  alert("Character'" + arrInvalidChars[i] + "' not allowed.");

  return; //跳出

  }

  }

  };

  JS 第七章 :COOKIE操作与样式表编程↑↓←→

  //Cookie简介

  {

  cookie是网站放在用户计算机上的一小块信息,分为: //例如: 手机QQ上的登录,点击记住用户名密码,下次就不同输入了,这就是Cookie做的

  

复制代码 代码如下:

  1、存入计算机内存(临时cookie)

  2、写入文件(持久cookies)

  路径 :C:\Documents and Settings\Administrator\Cookies

  }

  //Cookie的组成:

  

复制代码 代码如下:

  1.名称:每一个cookie由一个唯一的名称代表,不区分大小写

  2、值: 保存在Cookie中的字符串值,长度小于4KB

  3、域: 出于安全考虑,网站不能访问由其他域创建的cookie

  4、路径 :限制了对web服务器上的特定目录的访问

  5、失效日期 :cookie何时应该被删除

  6、安全标志: 一个bool值,用于表示cookie是否只能从安全网站(使用SSL和Https协议)中访问

  //安全限制

  

复制代码 代码如下:

  1、每个域(每一个网站)最多只能在一台用户机器上存储20个cookie

  2、每个cookie的尺寸不能超过4096字节

  3、一台用户机器上的cookie总数不能超过300个

  4、浏览器自身的安全机制: 阻止所有cookie、阻止未知网站的cookie或者创建cookie时给用户提示 (调试方法:工具→Internet选项→隐私→设置安全性级别)

  //写入cookie

  

复制代码 代码如下:

  cookie实际上是一个字符串,当页面载入时由浏览器自动生成。

  通过document对象的cookie属性可以操作。

  在cookie中,信息由分号隔开,通常每个cookie都包含了一对由等号分开的名字和值。

  fur=blue; food=biscuits; name=Cookie_Monster

  //cookie的写入有点类似于键值对的形式

  例子(cookieWrite)(设置cookie的过期时间(过期时间被添加到cookie的末尾))

  

复制代码 代码如下:

  src="javascript/cookieWrite.js"中的内容:

  var myCookie=new Object();

  myCookie.writeCookie = function(isLogin, isExpire)//isLogin表示登录成功 isExpire表示是临时还是持久cookie

  {

  var theCookie;

  if (isLogin == true && isExpire == true) { //写入永久cookie 注意:当创建自己的cookie字符串时,一定要确保名字和值不包括空格、逗号或者分号。这些字符会在解析cookie字符串的时候造成错误

  var date = new Date(Date.parse("May 1, 2010")); //Date.parse("日期") 是将一个日期转换为字符串

  theCookie = "isLogin=marssion" + ";Expires=" + date.toGMTString(); //date.toGMTString()方法点不出来 ,是将时间进一步进行转换成(GMT(格林威治时间表示法))类型的字符串格式

  document.cookie = theCookie; //Expires=拼成的一个字符串:表示的是过期时间,和前面的字符串用“;“隔开,理论上一个cookie只有一个等号(用户只能每次添加一个cookie,即使严格按照cookie串的格式将多个cookie拼接成一个大串,也无法将这个字符串加入到document.cookie中),加入过期时间是一个例外

  location.href = "cookieRead.htm"; //点击后跳转到相应的页面

  }

  else if (isLogin == true && isExpire == false) { //写入临时cookie

  theCookie = "isLogin=marssion";

  document.cookie = theCookie;

  location.href = "cookieRead.htm";

  }

  }

  ----------------------------------------------------------------

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/cookieWrite.js"></script>

  <script language="javascript" type="text/javascript">

  function CheckLogin()

  {

  var myvalue=document.getElementById("userName");

  var pwd=document.getElementById("password");

  if(myvalue.value=="marssion" && pwd.value=="1234") {

  WriteCookie(true);//true表示用户名密码正确,登录成功

  return true;

  }

  else

  {

  alert("UserName or Password error!");

  return false;

  }

  }

  function WriteCookie(islogin)

  {

  var myCheckBox=document.getElementById("remember");

  if(myCheckBox.checked==true)

  {

  myCookie.writeCookie(islogin,true);//写入持久cookie

  }

  else

  {

  myCookie.writeCookie(islogin,false);//写入临时cookie

  }

  }

  </script>

  </head>

  <body>

  <h1>Writing Cookies</h1>

  <h2>Look for the cookie in your cookie folder</h2>

  <h3>Location:"C:\Documents and Settings\[UserName]\Cookies"</h3>

  <form>

  UserName:<br /><input type="text" id="userName" /><br />

  Password:<br /><input type="password" id="password" /><br /><br />

  <input type="button" value="Submit" onclick="if(CheckLogin()==false) return false" />

  <input type="reset" value="Reset" /><br />

  Remember Me<input id="remember" type="checkbox" checked="checked" value="NoExpire" />

  </form>

  </body>

  </html>

  例子(cookieRead)

  

复制代码 代码如下:

  src="javascript/cookieRead.js"中的内容:

  var myCookie=new Object();

  myCookie.getCookie = function(searchName)

  {

  var cookies=document.cookie.split(";");//cookie里的字符串是用“;”分隔开的

  for(var i=0;i<cookies.length;i++)

  {

  var cookiecrumbs=cookies[i].split("="); //在把取出的字符串用“=”分隔开

  var cookiename=cookiecrumbs[0];

  var cookievalue=cookiecrumbs[1];

  if(cookiename==searchName)

  {

  return cookievalue; //将找到得相应的name的值返回去,每个cookie都有一个相应的txt文档,我们只需要将相应的cookie名字给出,在存放cookie的txt文件夹里有一个dat数据库文件,它会自动找到相应的txt文档

  }

  }

  return false;

  }

  -----------------------------------------------------------------------

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script language="javascript" type="text/javascript" src="javascript/cookieRead.js"></script>

  <script language="javascript" type="text/javascript">

  function load()

  {

  var isLogin=myCookie.getCookie("isLogin");

  if (isLogin == "marssion")

  {

  document.write("登陆成功。欢迎你!");

  }

  else

  {

  location.href="cookieWrite.htm";

  }

  }

  </script>

  </head>

  <body onload="load()">

  </body>

  </html>

  例子(页面上的超级链接鼠标移上去的时候下划线变为上划线)

  

复制代码 代码如下:

  addLoadListener(init);

  function init()

  {

  if(typeof document.styleSheets!="undefined") //document.styleSheets :当前引用的所有样式

  {

  addStyleRule(document.styleSheets[0],"a:hover","text-decoration:overline"); //需要引用<link rel="Stylesheet" type="text/css" href="aa1.css" />

  }

  return true;

  }

  function addStyleRule(styleSheet,selector,properties,index)

  {

  if(typeof styleSheet.addRule!="undefined")

  {

  styleSheet.addRule(selector,properties,index);

  }

  else if(typeof styleSheet.insertRule!="undefined")

  {

  if(typeof index=="undefined")

  {

  index=styleSheet.cssRules.length;

  }

  styleSheet.insertRule(selector+"{"+properties+"}",index);

  }

  return true;

  }

  function addLoadListener(fn)

  {

  if (typeof window.addEventListener != 'undefined')

  {

  window.addEventListener('load', fn, false);

  }

  else if (typeof document.addEventListener != 'undefined')

  {

  document.addEventListener('load', fn, false);

  }

  else if (typeof window.attachEvent != 'undefined')

  {

  window.attachEvent('onload', fn);

  }

  else

  {

  var oldfn = window.onload;

  if (typeof window.onload != 'function')

  {

  window.onload = fn;

  }

  else

  {

  window.onload = function()

  {

  oldfn();

  fn();

  };

  }

  }

  }

  //读取Cookie中Value的某个值

  

复制代码 代码如下:

  下面为外置JS文件中的内容:

  ---

  var cookieName = "monsterCookie";

  var cookieValue = "fur:blue/food:biscuits/name:monsterCookie";

  debugger;

  cookieValue=escape(cookieValue);//对cookie值进行编码

  var theCookie = cookieName + "=" + cookieValue;

  document.cookie=theCookie;

  var monsterName = getSubCookie("monsterCookie", "name");

  alert("The value of the sub-cookie 'name' is :"+monsterName);

  function getSubCookie(cookieName,subCookieName) {

  var cookies=document.cookie.split(";"); //先用分号进行拆分

  for(var i=0;i<cookies.length;i++)

  {

  var cookieCrumbs=cookies[i].split("="); //再用等号进行拆分

  if(cookieCrumbs[0]==cookieName) //如果cookieCrumbs[0](拆分出的名字)等于传入的名字

  {

  var cookieValue=cookieCrumbs[1]; //获得所需要的值

  cookieValue = unescape(cookieValue); //对cookie值进行解码

  var subCookies=cookieValue.split("/");

  for(var j=0;j<subCookies.length;j++)

  {

  var subCookieCrumbs=subCookies[j].split(":");

  if(subCookieCrumbs[0]==subCookieName)

  {

  return subCookieCrumbs[1];

  }

  }

  }

  }

  return false;

  }

  -------------------------------------------------------------------------

  //样式:

  //访问样式

  

复制代码 代码如下:

  使用style对象需要注意几个问题。

  样式设置必须符合CSS规范。

  如果样式属性名称中带“-”号,首字母大些。

  保留字,不能用作属性名称。

  使用style对象获取的属性与元素最终显示效果并不一定相同,因为除了内联样式声明之外,还可以通过<style>元素以及链接样式表的方式改变元素的显示效果

  例子(关于style属性值的拼写,和在IE火狐中的区别)

  

复制代码 代码如下:

  <html>

  <head>

  <title>Style Example</title>

  <script type="text/javascript">

  function sayStyle() {

  var oDiv = document.getElementById("div1");

  //alert(oDiv.style.cssFloat); //火狐 :css+...

  alert(oDiv.style.styleFloat); //IE:style+...

  //alert(oDiv.style.backgroundColor);//将‘-'去掉,将后一个单词首字母大写

  }

  </script>

  </head>

  <body>

  <div id="div1" style="background-color: red; height: 50px; width:

  50px;float:left"></div><br />

  <input type="button" value="Get Background Color" onclick="sayStyle()" />

  </body>

  </html>

  例子(变换层的颜色)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>无标题页</title>

  <script type="text/javascript" language="javascript">

  function aa()

  {

  var cr=document.getElementById("div1");

  cr.style.backgroundColor='orange';

  }

  function bb()

  {

  var cr=document.getElementById("div1");

  cr.style.backgroundColor="blue";

  }

  function cc()

  {

  var cr=document.getElementById("div1");

  var cc=cr.style.backgroundColor.toString(); //必须去对象,用this报错

  alert(cc);

  }

  </script>

  </head>

  <body>

  <div id="div1" style=" background-color:Red; height:50px; width:50px;" onmouseover="aa()" onmouseout="bb()"></div>

  <input type="button" value="Get Background Color" onclick="cc()" />

  </body>

  </html>

  -----------------------------------------------------

  或者上面等价于:

  <html>

  <head>

  <title>Style Example</title>

  <script type="text/javascript">

  function sayStyle() {

  var oDiv = document.getElementById("div1");

  alert(oDiv.style.backgroundColor);

  }

  </script>

  </head>

  <body>

  <div id="div1"

  style="background-color: red; height: 50px; width: 50px"

  onmouseover="this.style.backgroundColor= 'blue'"

  onmouseout="this.style.backgroundColor = 'green'"></div>

  <input type="button" value="Get Background Color" onclick="sayStyle()" />

  </body>

  </html>

  例子(将样式文本输出)

  

复制代码 代码如下:

  <html>

  <head>

  <title>Style Example</title>

  </head>

  <body>

  <div id="div1"

  style="background-color: red; height: 50px; width: 50px"

  onclick="alert(this.style.cssText)"></div> //this.style.cssText : background-color: red; height: 50px; width: 50px

  </body>

  </html>

  //通过Style对象读取单个样式的方法

  

复制代码 代码如下:

  getPropertyPriority() 如果css属性“important”定义在规则中则返回important,否则将返回空字符串

  Item(index) 按照序号来返回css属性中的名字

  removeProperty(propertyName) 从css定义中删除属性

  setProperty(propertyName,value,priority) 给css设置属性

  例子(属性的设置和移除(火狐能用))

  

复制代码 代码如下:

  <html>

  <head>

  <title>Style Example</title>

  <script type="text/javascript">

  function useMethods() {

  var oDiv = document.getElementById("div1");

  // IE不支持以下属性和方法

  alert(oDiv.style.item(0)); //outputs “background-color"

  alert(oDiv.style.getPropertyValue("background-color")); //得到当前的background-color值

  alert(oDiv.style.removeProperty("background-color")); //将background-color属性移除

  }

  </script>

  </head>

  <body>

  <div id="div1" style="background-color: red; height: 50px; width:50px"

  onmousemove="this.style.setProperty('background-color','blue','')" <!--setProperty("样式名(css格式)","样式值","给空就行了")-->

  onmouseout="this.style.setProperty('background-color','red','')"></div><br />

  <input type="button" value="Use Methods" onclick="useMethods()" />

  </body>

  </html>

  例子(动态改变字体的大小,用三元运算符使IE和火狐兼容)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>CSS Test</title>

  <!--<link rel="Stylesheet" type="text/css" href="css/a.css" />-->

  <style type="text/css">

  * { //*{} 应用所有

  font-family: Tahoma, Arial, serif; //.div{} (class选择器 应用所有的层)

  font-size: 18pt; //#id名{} (ID选择器)

  text-align: left;

  }

  .div {

  font-size: 30px;

  color: #FF4500;

  }

  </style> <!-- *{} 这是一个样式规则--> <!-- .div{} 这是一个样式规则-->

  <script language="javascript" type="text/javascript">

  var tag=false;

  function change() {

  // CSS样式规则的集合

  // 样式规则

  // ↓

  var cssRules = document.styleSheets[0].rules ? document.styleSheets[0].rules : document.styleSheets[0].cssRules; //此处三元运算符的作用是:让IE和火狐都能用 // 修改.div样式规则中的font-size样式

  // ↑ ↑

  // 当前引用的所有样式 三元运算符如果?前的结果返回的是true就执行:前的返回的是false就执行:后的

  if(tag==false)

  {

  cssRules[1].style.fontSize = "60px";

  tag=true;

  }

  else{

  cssRules[1].style.fontSize = "30px";

  tag=false;

  }

  }

  </script>

  </head>

  <body>

  <div id="div1" class="div">msg</div>

  <div id="div2" class="div">msg</div>

  <div id="div3" class="div">msg</div>

  <button onclick="change()">change</button>

  </body>

  </html>

  例子(切换样式表1)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>CSS Test</title>

  <link id="style1" type="text/css" rel="stylesheet" href="css/style1.css"title="white" />

  <link id="style2" type="text/css" rel="stylesheet" href="css/style2.css" title="gray" />

  <script language="javascript" type="text/javascript">

  getElement("style1").href = "";

  getElement("style2").href = "";

  function setStyle(title,sa) {

  // 首先禁用所有的样式表

  getElement("style1").href = "";

  getElement("style2").href = "";

  // 启用指定的样式表

  getElement(title).href = sa;

  }

  function getElement(id) {

  return document.getElementById(id);

  }

  </script>

  </head>

  <body>

  <div>

  <p>

  We would like to see as much CSS1 as possible.

  </p>

  <p>

  If your design doesn't work in at least IE5+/Win and Mozilla (run

  by over 90% of the population), chances are we won't accept it.

  </p>

  </div>

  <button onclick="setStyle('style1','css/style1.css')">white</button>

  <button onclick="setStyle('style2','css/style2.css')">gray</button>

  </body>

  </html>

  例子(切换样式表2)

  

复制代码 代码如下:

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>CSS Test</title>

  <link type="text/css" rel="stylesheet" href="css/style1.css" title="白色风格" id="style1" />

  <link type="text/css" rel="stylesheet" href="css/style2.css" title="灰色风格" id="style2" />

  <script language="javascript" type="text/javascript">

  function setStyle() {

  var option1 = document.getElementById("option1");

  var option2 = document.getElementById("option2");

  var style1 = document.getElementById(option1.value);

  var style2 = document.getElementById(option2.value);

  // 首先禁用所有的样式表

  style1.disabled = true;

  style2.disabled = true;

  // 启用指定的样式表

  if (option1.selected) {

  style1.disabled = false;

  }

  else {

  style2.disabled = false;

  }

  }

  </script>

  </head>

  <body>

  <select id="styleSel" onchange="setStyle()">

  <option value="style1" id="option1">白色风格</option>

  <option value="style2" id="option2">灰色风格</option>

  </select>

  <div>

  <p>

  We would like to see as much CSS1 as possible.

  </p>

  <p>

  If your design doesn't work in at least IE5+/Win and Mozilla (run

  by over 90% of the population), chances are we won't accept it.

  </p>

  </div>

  </body>

  </html>

  例子(点击层显示,点击层隐藏)

  

复制代码 代码如下:

  <html>

  <head>

  <title>Style Example</title>

  <script type="text/javascript">

  function toggle(sDivId) {

  var oDiv = document.getElementById(sDivId);

  oDiv.style.display = (oDiv.style.display == "none") ? "block" : //对象.style.display 显示状态:取值范围: "none(不显示)" "block(显示)"

  "none";

  }

  </script>

  </head>

  <body>

  <div style="background-color: blue; color: white; font-weight: bold;

  padding: 10px; cursor: pointer"

  onclick="toggle('divContent1')">Click Here</div>

  <div style="border: 3px solid blue; height: 100px; padding: 10px"

  id="divContent1">This is some content

  to show and hide.</div>

  <p> </p>

  <div style="background-color: blue; color: white; font-weight: bold;

  padding: 10px; cursor: pointer" <!-- cursor (指示鼠标的显示状态(pointer(手)))-->

  onclick="toggle('divContent2')">Click Here</div>

  <div style="border: 3px solid blue; height: 100px; padding: 10px"

  id="divContent2">This is some content

  to show and hide.</div>

  </body>

  </html>

  例子(鼠标移上,显示层)

  

复制代码 代码如下:

  <html>

  <head>

  <title>Style Example</title>

  <script type="text/javascript">

  function showTip(oEvent) {

  var oDiv = document.getElementById("divTip1");

  oDiv.style.visibility = "visible"; //对象.style.visibility 显示状态: 取值范围是:"visible(显示)" "hidden(不显示)" 和display用法相同,只是取值范围不同

  oDiv.style.left = oEvent.clientX + 5; //显示层的坐标(鼠标的横坐标+5)

  oDiv.style.top = oEvent.clientY + 5; //显示层的坐标(鼠标的纵坐标+5)

  }

  function hideTip(oEvent) {

  var oDiv = document.getElementById("divTip1");

  oDiv.style.visibility = "hidden";

  }

  </script>

  </head>

  <body>

  <p>Move your mouse over the red square.</p>

  <div id="div1"

  style="background-color: red; height: 50px; width: 50px"

  onmouseover="showTip(event)" onmouseout="hideTip(event)"></div>

  <div id="divTip1"

  style="background-color: yellow; position: absolute; visibility:

  hidden; padding: 5px">

  <span style="font-weight: bold">Custom Tooltip</span><br />

  More details can go here.

  </div>

  </body>

  </html>