JavaScript 对象详解重要

一、Array数组对象

一、声明数组的方法:
1、var arr = new Array();
   arr[0] = "1";
   arr[0] = "2";

2、var arr = new Array(4,23,2,323,asdf);

3、var arr = ["aaa", "bbb", {name:"guang", age:"28"}];

 
一、属性:

1constructor:返回对创建此对象的数组函数的引用。

var test=new Array();

if (test.constructor==Array){

  document.write("This is an Array");

}

if (test.constructor==Boolean){

  document.write("This is a Boolean");

}

if (test.constructor==Date){

  document.write("This is a Date");

}

   

2length:返回数组中元素的数目。

var arr = new Array("aaa", "bbb", "ccc");
arr.length;

3、prototype:实现

 

 

二、方法

1、 push()可以在数组的末尾插入一个或多个元素,并返回新的长度

var a = []; //建立数组 
a.push ("a");
a.push ("b");
a.push ("c");
alert(a); //结果是a,b,c;

 

2、 pop()用于删除数组的最后一个元素

var arr = new Array("百度","腾讯QQ","网易");

document.write(arr.pop()+"<br>");    // 输出网易

document.write(arr);                 // 输出百度,腾讯QQ

 

3、 shift()用于把数组的第一个元素从其中删除,并返回第一个元素的值

var Arr = new Array("土豆网","优酷网","网易")

document.write(Arr+"<br />");               // 输出土豆网,优酷网,网易

document.write(Arr.shift() +"<br />");  // 输出土豆网

document.write(Arr);                        // 输出优酷网,网易

 

4、 unshift()可以将一个或多个元素插入到数组的头部

var arr = new Array("土豆网","优酷网")

document.write(arr.unshift("网易") + "<br />")   //输出网易,土豆网,优酷document.write(arr.unshift('aa','bb','cc') +"<br />");

//输出网易,土豆网,优酷,aa,bb,cc

 

5、 join()可以把一个数组的所有元素都转换成字符串,然后把它们连接起来并以逗号分割.

    var a = [1,2,3];

    var s = a.join();                   // 输出字符串的1,2,3

 

6、 reverse()将颠倒的数组元素的顺序并返回颠倒后的数据。

var arr = new Array('凤翔俯','承天门','三贤府')

document.write(arr.reverse());
// 输出三贤府,承天门, 凤翔俯

 

7、 sort()在原数组上对数组元素进行排序

注:

若 a 小于 b,在排序后的数组中 a 应该出现在b 之前,则返回一个小于 0 的值。

若 a 等于 b,则返回 0。

若 a 大于 b,则返回一个大于 0 的值。

function sortNumber(a,b){

return a - b

}

var arr = new Array("10","5","40","25","1000","1");

document.write(arr + "<br />")          // 10,1000,20,40,5

document.write(arr.sort(sortNumber))    // 5,10,20,40,1000

 

    例2:

var arr = new Array("10","5","40","25","1000","1");

document.write(arr.sort())          // 1,10,1000,20,40,5

 

9concat()用于连接两个或多个数组,并创建返回一个数组.

var arr = new Array("中彩网","赶集网北京","北青网");

document.write(arr.concat("中央电视台","早报网");      

// 输出中彩网,赶集网北京,北青网,中央电视台,早报

 

10slice()数组由第一个参数指定的元素到第二个元素为目,例如参数-1指定数组最后一个元素,-3就是倒数第三个。

var color = new Array('red','blue','yellow','black');
var color2 = color.slice(1,2);
alert(color);   //输出 red,blue,yellow,black
alert(color2); //输出 blue;注意:这里只有第二项一个值

11splice(index,howmany,element1,…,elementX)用于插入、删除或替换数组的元素 

splice是JS中数组功能最强大的方法,它能够实现对数组元素的删除、插入、替换操作,返回值为被操作的值。

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

splice删除:  color.splice(1,2) (删除color中的2和3两项); 参数1:指定数组的索引 参数2:要删除几项
删除指定下标的元素:

  var arr = ["George", "John", "Thomas", "James", "Adrew", "Martin"]
  arr.splice(2, 1);   // 只删除第三项,注第二个参数要为1
  console.log(arr)  // 返回"George", "John", "James", "Adrew", "Martin"

splice插入:  color.splice(1,0,'brown','pink') (在color键值为1的元素前插入两个值);

splice替换:  color.splice(1,2,'brown','pink') (在color中替换1、2元素);

var color = new Array('red','blue','yellow','black');
var color2 = color.splice(2,3,'brown','pink');
alert(color); // red,blue,brown,pink
alert(color2); // yellow,black

  

12toString()将数组中每一个元素都转换成字符串,并返回结果。

    var arr = [1,2,3].toString();

   

13toLocaleString()toString()方法的本地化,下面的例子就说明来查看本计算机的日期

 var d, s;                      // 声明变量。

 d = new Date();                // 创建 Date 对象。

 s = "Current setting is ";

 s += d.toLocaleString();       // 转换为当前区域。

 return(s);                     // 返回转换的日期。

实例:

一、让数组里的内容随机排列

$(function () {
    var firstArr = ["HTML","XHTML","CSS","JavaScript","JSON","RIA","jQuery"];
    var lastArr = [];

    for(var i=firstArr.length; i>=1; i--){
        // 随机提取数组里的数
        var len = Math.floor(Math.random()*firstArr.length);
        lastArr.push(firstArr[len]);
        firstArr.splice(len,1)
    }

    for(var i=0; i<lastArr.length; i++){
        $("#test1").append(lastArr[i]+"");
    }
})

二、String字符串对象

JavaScript转义符

转义序列字符
\b 退格
\f 走纸换页
\n 换行
\r 回车
\t 横向跳格 (Ctrl-I)
\' 单引号
\" 双引号
\\ 反斜杠

 

一、属性:

1、length:字符串长度

var str = "国羽曝四短板";
alert(str.length);

 

2、constructor:

3、prototype:

 

 

二、方法:


1、anchor() :方法用于创建 HTML 锚

  var txt="Hello world!"

  document.write(txt.anchor("myanchor"))

 

2big() :方法用于把字符串显示为大号字体

  var str="Hello world!"

  document.write(str.big())

 

3blink() 方法用于显示闪动的字符串

 

4bold()方法用于把字符串显示为粗体

 

5charAt() :方法可返回指定位置的字符。

  var str="Hello world!"

  document.write(str.charAt(1))   // 返回e   参数下标从0开始

 

6charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。

  var str="Hello world!"

  document.write(str.charCodeAt(1))   // 输出101  e的Unicode码为101

 

7indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果没有查找到返回-1

   var str="Hello world!"


  document.write(str.indexOf("Hello") + "<br />")     // 0


  document.write(str.indexOf("World") + "<br />")     // -1


  document.write(str.indexOf("world"))                // 6

 

8lastIndexOf()方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。

 

9concat() 方法用于连接两个或多个字符串

  var str1="Hello "

  var str2="world!"

  document.write(str1.concat(str2));  // 输出 Hello world;

10replace()用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

var str = "让宝宝吃饭不再成为头痛的难题";

document.write(str.replace(/宝宝/,"孩子"));     // 输出让孩子吃饭不再成为头痛的难题

// 或者第一个参数可以写字符串:

var getNode = document.getElementsByTagName("a")[0].innerHTML;
var newNode = getNode.replace("卫生厅","派出所");
document.getElementsByTagName("a")[0].innerHTML = newNode;


 

11search()检索与正则表达式相匹配的值。如果没有匹配返回-1

var str="Visit W3School!"

document.write(str.search(/W3school/))      // 输出6

document.write(str.search(/w3school/))      // 输出-1

// 第一个参数可以定字符串
var getNode = document.getElementsByTagName("a")[0].innerHTML;
var newNode = getNode.search("卫生厅");
document.getElementsByTagName("a")[0].innerHTML = newNode;

 

12slice(开始,结束) 方法可提取字符串的某个部分,并以新的字符串返回被提取的部分。

  var str="Hello happy world!"

  document.write(str.slice(6))        // 输happy world!

  var str="Hello happy world!"

  document.write(str.slice(6,11)) // 提取第六个字符到第11个字符 输出happy

13split()方法用于把一个字符串分割成字符串数组。输出正常以符号相分隔。

var str="How are you doing today?"

document.write(str.split(" ") + "<br />")       //  输出How,are,you,doing,today?

document.write(str.split("") + "<br />")        // 输出H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?

document.write(str.split(" ",3))            // 输出How,are,you

 

14、substr(start,length) 方法可在字符串中抽取从 start 下标开始的指定数目的字符。如果start-1,则是从最后一个字符开始,如果-2,则倒数第二个字符开始

    var str="[精彩动画]让好听的儿歌伴宝宝快乐长大";

    document.write(str.substr(3,7));            // 输出 动画]让好听的

  

15、fixed() 方法用于把字符串显示为打字机字体

  var str="Hello world!"

  document.write(str.fixed())

 

16fontcolor() 方法用于按照指定的颜色来显示字符串


17
fromCharCode() 可接受一个或多个指定的 Unicode 值,然后返回一个字符串

  document.write(String.fromCharCode(72,69,76,76,79))

  document.write("<br />")

  document.write(String.fromCharCode(65,66,67))

 

18italics() 方法用于把字符串显示为斜体

19link()方法用于把字符串显示为超链接。

20localeCompare()用本地特定的顺序来比较两个字符串。

 

21match()方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。如果找到输出这个值,如果没检索到输出null

  var str="Hello world!"

  document.write(str.match("world") + "<br />")   // 输出world

  document.write(str.match("World") + "<br />")   // 输出null

  document.write(str.match("world!"))         // 输出world!

 

  var str="1 plus 2 equal 3"

  document.write(str.match(/\d+/g))       // 输出 1,2,3

 

22small() 方法用于把字符串显示为小号字

 

23strike() 方法用于显示加删除线的字符串

 

24sub() 方法用于把字符串显示为下标

 

25toLocaleLowerCase()把字符串转换为小写

 

26toLocaleUpperCase():把字符串转换为大写。

 

27toLowerCase()把字符串转换为小写。

 

28toUpperCase():把字符串转换为大写

 

29toString()

 

30valueOf() 方法可返回 String 对象的原始值。

 

31parseInt(string)将字符串提出字数,也可以将小数变成正数。

32parseFloat(string)

三、Window对象

一、Window大写表示浏览器窗口对象,而小写window表示窗口句柄

1、window                          // 窗口自身  
2、window.self                    // 引用本窗口window=window.self 
3、window.closed                // 表示窗口是否已经关闭

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


二、对象方法
7、window.alert("text")                     //提示信息对话框

8、window.confirm("text")                 //确认对话框

9、window.prompt("text")                 //要求键盘输入对话框

10、window. setInterval("action",time)  //每隔指定的时间(毫秒)就执行一次操作

11、window.clearInterval()                //清除时间设置作用就是终止循环

12、window.setTimeout(action,time)     //隔了指定的时间(毫秒)执行一次操作

13、window.open()                       //打开新的窗口

14、window.close()                       //关闭脚本所在窗口

15、window.alert()                        //弹出简提示

16、window.blur()                         //窗口失去焦点

17、window.focus()                       //窗口获得焦点

18、window.moveBy()                    //移动窗口

19、window.moveTo()                    //移动窗口

20、window.navigate()                   //浏览某个URL

21、window.print()                        //打印当前窗口文档内容

22、window.prompt()                    //询问对话框

23、window.resizeBy()                   //改变窗口大小

24、window.resizeTo()                   //改变窗口大小

25、window.scroll()                        //控制滚动条

26、window.scrollBy()                    //控制滚动条

27、window.scrollTo()                    //控制滚动条

 

三、对象属性

1、window.clientInformation             //客户端信息

2、window.clipboardData                 //剪贴板数据

3、window.closed                           //当前窗口是否关闭

4、window.defaultStatus                 //设定窗口状态栏信息

5、window.dialogArgument              //模态对话框参数

6、dialogHeight                              //模态对话框高度

7、dialogLeft                                  //模态对话框左上角横坐标

8、dialogTop                                  //模态对话框左上角纵坐标

9、dialogWidth                               //模态对话框宽度

10、window.document                     //当前窗口的Document对象引用

11、window.event                           //事件参数

12、window.frameElement                 //窗口框架元素引用

13、window.frames                         //当前窗口中的框架

14、window.history                        //当前窗口中的History对象引用

15、window.images                       //当前窗口中的图片引用

16、window.length                        //当前窗口的框架的数量

17、window.location                      //URL地址,设置这个属性可以打开新的页面

18、window.name                         //为窗口命名

19、window.navigator                   //当前窗口的Navigator对象引用

20、window.opener                      //父窗口引用

21、window.resizable                    //窗口是否允许改变大小

22、window.screenLeft                 //屏幕偏移量

23、window.scrrenTop                  //屏幕偏移量

24、window.self                            //当前窗口自身引用 


四、成员对象
window.event
window.document                         //见document对象详解
window.history
window.screen
window.navigator
window.external

 


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

 


五、window.history历史对象

window.history.length                   //浏览过的页面数
history.back()                          //后退
history.forward()                       //前进
history.go(i)                           //到历史清单的第i位
                                        //i>0前进,i<0后退
---------------------------------------------------------------------

 


六、window.screen对象

window.screen.width                   //屏幕宽度

window.screen.height                 //屏幕高度

window.screen.colorDepth           //屏幕色深

window.screen.availWidth            //可用宽度

window.screen.availHeight           //可用高度(除去任务栏的高度)


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

 


七、window.external对象

window.external.AddFavorite("地址","标题" )    //把网站添加到收藏夹

 

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

 


八、window.navigator浏览器对象

navigator.appCodeName       // 浏览器代码名  :appCodeName:Mozilla

navigator.appName              // 浏览器的名称  :appName:Netscape

navigator.appVersion           // 浏览器版本(包括系统版本)也包括了appName和appCodeName中的所有信息

navigator.platform               // 操作系统类型 win32

navigator.appMinorVersion   // 浏览器补丁版本

navigator.cpuClass              // cpu类型 x86

navigator.plugins

navigator.opsProfile

navigator.userProfile

navigator.systemLanguage //客户系统语言 zh-cn简体中文

navigator.userLanguage      //用户语言,同上

navigator.userAgent

navigator.onLine                 //用户否在线

navigator.cookieEnabled      //浏览器是否支持cookie

navigator.mimeTypes

 

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

 

 

九、Location对象

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

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

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

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

5、reload() 重新加载当前页

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

7、location.pathname  返回 --返回 /test/test.htm

 

1.1    BOM

 


    BOM提供了一组以window为核心的对象,实现了对浏览器窗口的访问控制。BOM中定义了6种重要的对象:

 

    •  window对象表示浏览器中打开的窗口;
    • document对象表示浏览器中加载页面的文档对象;
    • location对象包含了浏览器当前的URL信息;
    • navigation对象包含了浏览器本身的信息;
    • screen对象包含了客户端屏幕及渲染能力的信息;
    • history对象包含了浏览器访问网页的历史信息。
    除了window对象之外,其他的5个对象都是window对象的属性,它们的关系如下图:

 

 

 

1.1.1    window对象


    window对象就是JavaScript的Global对象,所以在使用window对象的属性和方法是不需要特别指明。如:alert,实际上完整的 调用是window.alert,通常省略了window对象的引用。window对象提供的主要功能有:调整窗口的尺寸和位置、打开新窗口、系统提示 框、状态栏控制、定时操作,下面分别对这5个功能详细讲述。
 

 

 

 

            1.    调整窗口的尺寸和位置            

 

方法

用法

说明

window.moveBy

将浏览器窗口移动到指定位置(相对定位)

window.moveBy(dx,dy)

出于安全性和对用户有好的考虑,不允许使用JavaScript脚本将窗口移动到可视区域之外,必须始终保证浏览器窗口在屏幕的可视区域。

window.moveTo

将浏览器窗口移动到指定位置

(绝对定位)

window.moveBy(x,y)

如果指定的坐标(x,y)会使部分或全部窗口置于可视区域之外,那么窗口将停留在最接近屏幕边缘的位置。

window.resizeBy

将浏览器窗口的尺寸改变指定的宽度和高度(相对调整窗口大小)

window.resizeBy(dw,dh)

window.resizeTo

将浏览器窗口的尺寸改变指定的宽度和高度(绝对调整窗口大小)

window.resizeTo(w,h)

指定的宽度和高度不能为负数

 

 

             2.    打开新窗口

 

                 用法:window.open([url],[target],[options])   

 

                    参数url:打开新新窗口将要加载的url。如果未指定参数,将默认加载空白页。如:window.open("test.htm");

 

                    参数target:新打开窗口的定位目标或者名称

 

                        _self       在当前窗口加载新页面

 

                        _blank    在新窗口加载新页面

 

                        _parent   在父窗口加载新页面

 

                        _top        在顶层窗口加载新页面       

 

                    参数options:新打开窗口的属性,是由若干个选项组成,选项之间用逗号分隔开,每个选项都包含了选项的名称和值。        

 

选项

说明

height

窗口的高度,单位像素

width

窗口的宽度,单位像素

left

窗口的左边缘位置

top

窗口的上边缘位置

fullscreen

是否全屏,默认值no

location

是否显示地址栏,默认值yes

menubar

是否显示菜单栏,默认值yes

resizable

是否允许改变窗口大小,默认值yes

scrollbars

是否显示滚动条,默认值yes

status

是否显示状态栏,默认值yes

titlebar

是否显示标题栏,默认值yes

toolbar

是否显示工具条,默认值yes

 

      window.open简单示例:

 

  第一个页面代码:

 

    

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>打开新窗口示例</title>
5 <style type="text/css">
6 #editor
7      {
8 width:300px;
9      }
10 #title, #editor textarea
11      {
12 width:100px;
13 height:80%;
14      }
15 </style>
16 <script type="text/javascript">
17     function newWin() {
18       //打开新窗口
19       var win = window.open("windowtwo.htm", "_blank", "toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400, height=300");
20     }
21   </script>
22 </head>
23 <body>
24 <form action="#">
25 <div id="editor">
26 标题:
27 <input type="text" id="title" /><br />
28 内容:
29 <textarea cols="30" rows="5" id="content"></textarea><br />
30 <input type="button" value="提交" />
31 <input type="button" value="在新窗口中编辑" onclick="newWin()" />
32 </div>
33 </form>
34 </body>
35 </html>

 

第二个页面代码:

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>新窗口</title>
5 <style type="text/css">
6 #editor
7      {
8 width:300px;
9      }
10 #title, #editor textarea
11      {
12 width:100%;
13 height:80%;
14      }
15 </style>
16 <script type="text/javascript">
17   function newWindow() {
18     //父窗口
19     var parent = window.opener;
20     if (!parent) {
21       return;
22   }
23     //从父窗口中获取标题和内容,填入子窗口的相应位置
24    $("title").value = parent.document.getElementById("title").value;
25   $("content").value = parent.document.getElementById("content").value;
26   }
27
28   function $(id) {
29     return document.getElementById(id);
30   }
31 </script>
32 </head>
33 <body onload="neWindow()">
34 <form action="#">
35 <div id="editor">
36 标题:
37 <input type="text" id="title" />
38 内容:
39 <textarea cols="30" rows="5" id="content"></textarea>
40 <input type="button" value="提交" />
41 <input type="button" value="在新窗口中编辑" onclick="neWin()" />
42 </div>
3.    系统提示框
    • window.alert   显示消息提示框,用法 window.alert([Message]); (注:一般都省略window对象,直接使用alert)
    •  window.confirm   显示一个确认对话框,其中包括“确定”和“取消”按钮。         

                        小示例:用户单击"确定"按钮时,window.confirm返回true,用户单击"取消"按钮时,window.confirm返回false。     

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>confirm示例</title>
6 <script type="text/javascript">
7     if(window.confirm("确定关闭窗口?"))
8 alert("true");
9     else
10 alert("false");
11   </script>
12 </head>
13 <body>
14 </body>
15 </html>
    • window.prompt   显示一个消息提示框,其中包含一个文本输入框。                

                        用法:window.prompt([Message],[default]);      Message是显示在提示框上的文本,default是设置文本框的默认值。如图:

          

            4.    状态栏控制

                    通过window.status属性进行控制。如:window.status="错误提示";    这样做会影响用户体验,所以不建议对状态栏信息进行修改。  

     5.    定时操作   

                    定时操作是web开发中常用功能,在基于Ajax技术的开发中,有一类应用需要定时的访问后台服务器并且更新前台页面,这类应用实现通常依赖于定时操作函数。

                    定时操作函数有四个:window.setInterval、window.clearInterval、window.setTimeout、window.clearTimeout,这四个函数都是window对象的方法,这说明浏览器中的定时操作是有浏览器窗口完成的。下面对这四种方法的用法详细介绍

      •    window.setInterval     设置定时器,每隔一段时间执行指定的代码    window.setInterval(code,time);

                                 说明: code参数可以是一个函数,也可以是一个字符串形式的JavaScript代码

                                            time参数是执行代码的时间间隔,单位是ms。

                                示例:           

1 <script type="text/javascript">
2 window.setInterval(function(){
3 alert("定时器");
4 },5000);
5 </script>
      •    window.clearInterval    清除setInterval函数设置的定时器    window. clearInterval(time); 、                       

            示例:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title></title>
5 <script type="text/javascript">
6     //定时器
7     var timer;
8     //开始计数
9     function startCount() {
10        //timer将保存计数器的ID
11 timer = window.setInterval(function () {
12          //从div中取得当前计数值
13          var divid = document.getElementById("counter");
14           var num = Number(divid.innerHTML);
15          //计数值加1,更新页面
16 divid.innerHTML = String(num + 1);
17 },1000);
18 }
19
20      //停止计数
21      function pause() {
22 window.clearInterval(timer);
23 }
24 </script>
25 </head>
26 <body>
27 <div id="counter">0</div>
28 <input type="button" onclick="startCount()" value="开始计数" />
29 <input type="button" onclick="pause()" value="停止计数" />
30 </body>
31 </html>
      •    window.setTiimeout    设置定时器,每隔一段时间执行指定的代码    window.setTiimeout(code,time);

                                 说明: code参数可以是一个函数,也可以是一个字符串形式的JavaScript代码,setTiimeout与setInterval区别在于setTiimeout对指定的代码只执行一次。

                                            time参数是执行代码的时间间隔,单位是ms。

                                示例:

1 <script type="text/javascript">
2 window.setTimeoutl(function(){
3 alert("setTimeout");
4 },5000);
5 </script>
      •    window.clearTimeout     清除 setTiimeout 函数设置的定时器    window. clearTimeout(time);    

            示例:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title></title>
5 <script type="text/javascript">
6     //定时器
7     var timer;
8     //开始计数
9     function startCount() {
10       //从div中取得当前计数值
11       var divid = document.getElementById("counter");
12       var num = Number(divid.innerHTML);
13       //计数值加1,更新页面
14 divid.innerHTML = String(num + 1);
15       //为了让setTimeout在执行一次后继续执行
16 timer = window.setTimeout(startCount, 1000);
17 }
18
19     //停止计数
20     function pause() {
21 window.clearTimeout(timer);
22 }
23 </script>
24 </head>
25 <body>
26 <div id="counter">0</div>
27 <input type="button" onclick="startCount()" value="开始计数" />
28 <input type="button" onclick="pause()" value="停止计数" />
29 </body>
30 </html>

43 </form>
44 </body>
45 </html>

 

效果如下:

 

 

四、Date对象

一、时间对象

① var myDate=new Date();//通过这一声明可以获得当前的时间

② var myDate=new Date(“month dd,yyyy hh:mm:ss”);

③ var myDate=new Date(“month dd,yyyy”);

④ var myDate=new Date(yyyy,mth,dd,hh,mm,ss);

⑤ var myDate=new Date(yyyy,mm,dd);

⑥ var myDate=new Date(ms);

 

需要注意最后一种形式,参数表示的是需要创建时间和GMT时间1970年1月1日之间相差的毫秒数。各种参数的含义如下:

·month:用英文表示的月份数,从January~December

·mth:用整数表示的月份。

·dd:表示一个月中的第几天

·yyyy:四位数表示的年份

·hh:小时数

·mm:分钟数

·ss:秒数

·ms:毫秒数

例:

var myDate=new Date(“May  21,2011 10:20:20”);

var myDate=new Date(“May  21 ,2011”);

var myDate=new Date(2011,11,21,12,12);

var myDate=new Date(2011,11,11);

var myDate=new Date(1178899200000);

 

二、常用方法

日期获取类函数

1、getFullYear():得到年

2、getYear() :得到date对象的年份(真实年份减去1900)

3、getMonth():得到月 (0-11)

4、getDate():得到日 (1-31)

5、getHours():得到小时 (0-23)

6、getMinutes():得到分钟(0-59)

7、getSeconds():得到秒(0-59)

8、getDay():得到星期几(0-6,0为星期日)

9、getTime():得到从1970年1月1日0:0:0到现在一共耗费的毫秒数

10、getUTCDate():返回date对象中用世界标准时间(UTC)表示的月份中的一天(1-31)

11、getUTCDay():返回date对象中用世界标准时间(UTC)表示的周中的一天(0-6)

12、getUTCFullYear():返回date对象中用世界标准时间(UTC)表示的四位年份

13、getUTCHours():返回date对象中用世界标准时间(UTC)表示的小时数(0-23)

14、getUTCMilliseconds():返回date对象中用世界标准时间(UTC)表示的毫秒数(0-999)

15、getUTCMinutes():返回date对象中用世界标准时间(UTC)表示的分钟数(0-59)

16、getUTCMonth():返回date对象中用世界标准时间(UTC)表示的月份数(0-11)

17、getUTCSeconds():返回date对象中用世界标准时间(UTC)表示的秒数(0-59)

 

日期设置类函数

18、setYear()                设置年

19、setMonth()           设置月

20、setDate()               设置日

21、setHours()             设置小时

22、setMinutes()        设置分钟

23、setSeconds()         设置秒

24、setTime()               设置从1970年1月1日0:0:0到现在一共耗费的毫秒数

 



根据一个或多个数值建立时间对象, 及本地计时与世界标准计时的区别


//先用最容易理解的方式建立一个时间对象
var d = new Date(2009, 2, 27, 12, 59, 59, 999);

alert(d);                      //Fri Mar 27 12:59:59 UTC+0800 2009  
alert(d.toString());           //Fri Mar 27 12:59:59 UTC+0800 2009
alert(d.toUTCString());        //Fri, 27 Mar 2009 04:59:59 UTC
alert(d.toLocaleString());     //2009年3月27日 12:59:59

alert(d.toDateString());       //Fri Mar 27 2009 
alert(d.toLocaleDateString()); //2009年3月27日 

alert(d.toTimeString());       //12:59:59 UTC+0800 
alert(d.toLocaleTimeString()); //12:59:59

/* 时间在计算机中被记为一个整数, 这是从 UTC 时间的 1970-1-1 0:0:0 到此时间的毫秒数 */
alert(d.valueOf());            //1238129999999
alert(d.getTime());            //1238129999999

/* 获取本地时间和世界标准计时的时差 */
alert(d.getTimezoneOffset()); //-480; 单位是分钟, 也就是 8 小时

/* 直接使用时间值(毫秒数, 譬如上面的: 1238129999999)建立时间对象 */
var d = new Date(1238129999999);
alert(d.toLocaleString());     //2009年3月27日 12:59:59 

/* 但建立函数有 2-7 个参数时, 将是根据 "年, 月, 日, 时, 分, 秒, 毫秒" 建立时间 */
d = new Date(2009, 2, 27, 12, 59, 59, 999);
alert(d.toLocaleString());     //2009年3月27日 12:59:59 

d = new Date(2009, 2, 27, 12, 59, 59);
alert(d.toLocaleString());     //2009年3月27日 12:59:59 

d = new Date(2009, 2, 27, 12, 59);
alert(d.toLocaleString());     //2009年3月27日 12:59:00   

d = new Date(2009, 2, 27, 12);
alert(d.toLocaleString());     //2009年3月27日 12:00:00  

d = new Date(2009, 2, 27);
alert(d.toLocaleString());     //2009年3月27日 0:00:00 

d = new Date(2009, 2);
alert(d.toLocaleString());     //2009年3月1日 0:00:00 

/* Date 类的静态函数 UTC 的参数也是和上面一样的 2-7 个, 但 UTC 获取的是个 number */
var n = Date.UTC(2009, 0); //这只是获取了那个表示时间的毫秒数
alert(typeof n);           //number

var d = new Date(n);       //根据刚刚获取的数、重新建立为时间对象
alert(d.toUTCString());    //Thu, 1 Jan 2009 00:00:00 UTC 
alert(d.toLocaleString()); //2009年1月1日 8:00:00 


无参数建立的时间对象、和用全局函数 Date 获取的时间的区别


var d1 = new Date(); //返回时间对象
var d2 = Date();     //返回时间字符串

alert(d1);           //Fri Feb 27 13:20:58 UTC+0800 2009
alert(d2);           //Fri Feb 27 13:20:58 2009 

alert(d1.valueOf()); //1235712058340
alert(d2.valueOf()); //Fri Feb 27 13:20:58 2009 

alert(typeof d1);    //object
alert(typeof d2);    //string

//明显看出 d2 只是字符串, 它可以使用 String 类的方法, 而不能使用 Date 类的方法.


使用字符串参数建立时间对象


var d;
d = new Date('Fri Mar 27 12:59:59 UTC+0800 2009');
alert(d.toLocaleString());     //2009年3月27日 12:59:59

d = new Date('Fri Mar 27 12:59:59 2009');
alert(d.toLocaleString());     //2009年3月27日 12:59:59

d = new Date('Fri Mar 27 2009');
alert(d.toLocaleString());     //2009年3月27日 0:00:00

d = new Date('Mar 27 2009');
alert(d.toLocaleString());     //2009年3月27日 0:00:00

/* 可使用 Date() 返回的字符串 */
var ts = Date();
d = new Date(ts);
alert(d.toLocaleString());     //2009年3月27日 14:04:38

/* Date 类的静态函数 parse 也是需要一样的字符参数, 不过它返回的是个数字(那个毫秒数) */
var n;
n = Date.parse('Mar 27 2009');
alert(n);                     //1238083200000 
alert(typeof n);              //number

d = new Date(n);
alert(d.toLocaleString());    //2009年3月27日 0:00:00


分别获取和设置: 年、月、日、时、分、秒、毫秒, 其中 "星期几" 可获取但不能设置


var d = new Date(2009, 2, 27, 12, 58, 59, 999);
alert(d.toLocaleString());  //2009年3月27日 0:00:00
alert(d.getFullYear());     //2009
alert(d.getMonth());        //2 (从 0 起, 2 指 3 月)
alert(d.getDate());         //27
alert(d.getDay());          //5 (星期五)
alert(d.getHours());        //12
alert(d.getMinutes());      //58
alert(d.getSeconds());      //59
alert(d.getMilliseconds()); //999 (毫秒)

d.setFullYear(2010);
d.setMonth(1);
d.setDate(2);
d.setHours(3);
d.setMinutes(4);
d.setSeconds(5);
d.setMilliseconds(6);

alert(d.toLocaleString());  //2010年2月2日 3:04:05
alert(d.getFullYear());     //2010
alert(d.getMonth());        //1 (从 0 起, 1 指 2 月)
alert(d.getDate());         //2
alert(d.getDay());          //2 (星期二)
alert(d.getHours());        //3
alert(d.getMinutes());      //4
alert(d.getSeconds());      //5
alert(d.getMilliseconds()); //6 (毫秒)

/* 还有一个 setTime */
var d = new Date();
d.setTime(0);
alert(d.toUTCString()); //Thu, 1 Jan 1970 00:00:00 UTC 

 

 

五、Math数学对象

 Math 和其他类不同, 它没有建立方法(不能这样使用: new Math()), 它的所有方法都是静态的(都得挂名调用).


1、Math.abs;    //绝对值
2、
Math.max;    //两个数中的大者 3、Math.min;    //两个数中的小者 4、Math.random; //随机数 5、Math.round;  //四舍五入 6、Math.ceil;  //上舍入 7、Math.floor;  //下舍入 8、Math.exp;    //e 的指数 9、Math.log;    //自然对数 10、Math.pow;    //x 的 y 次方 11、Math.sqrt;  //平方根 12、Math.sin;    //正弦 13、Math.cos;    //余弦 14、Math.tan;    //正切 15、Math.asin;  //反正弦 16、Math.acos;  //反余弦 17、Math.atan;  //反正切 18、Math.atan2;  //从 X 轴到一个点的角度


Math 类的还有八个常数


alert(Math.E);       //2.718281828459045  - 自然对数的底数
alert(Math.LN10);    //2.302585092994046  - 10 的自然对数
alert(Math.LN2);     //0.6931471805599453 - 2 的自然对数
alert(Math.LOG10E);  //0.4342944819032518 - 以 10 为底的 e 的对数
alert(Math.LOG2E);   //1.4426950408889633 - 以 2 为底的 e 的对数
alert(Math.PI);      //3.141592653589793  - π
alert(Math.SQRT1_2); //0.7071067811865476 - 2 的平方根除 1
alert(Math.SQRT2);   //1.4142135623730951 - 2 的平方根


部分测试


/* 获取 100 以内的随机数 */
var n1, n2;
n1 = Math.ceil(Math.random()*100);
n2 = Math.ceil(Math.random()*100);
alert(n1); //9
alert(n2); //80

/* pow */
alert(Math.pow(2, 3));     // 8
alert(Math.pow(1.5, 2.4)); // 2.6461778006805154

/* round、ceil、floor*/
var x = 1.45;
alert(Math.round(x));  // 1
alert(Math.ceil(x));   // 2
alert(Math.floor(x));  // 1
x = -1.45;
alert(Math.round(x));  // -1
alert(Math.ceil(x));   // -1
alert(Math.floor(x));  // -2

 

 

六、Document文档对象

一、属性

1、title:当前文档标题,如果未定义,则包含"Untitled".  

2、location:文档的全URL.  

3、domain:文档页面的Web服务器所在的域

3、lastModified:含有文档最后修改日期.  

4、referrer:调用者URL,即用户是从哪个URL链接到当前页面的.  通常获取页面来源的地址

5、bgColor:背景色(#xxxxxx)  

6、fgColor:前景文本颜色.  

7、linkColor:超链接颜色.  

8、vlinkColor:访问过的超链颜色.  

9、alinkColor:激活链颜色(鼠标按住未放时).  

10、forms[]:文档中form对象的数组,按定义次序存储.  

11、forms.length:文档中的form对象数目.  

12、links[]:与文档中所有HREF链对应的数组对象,按次序定义存储.  

13、links.length:文档中HREF链的数目.  

14、anchors[]:锚(...)数组,按次序定义存储.  

15、anchors.length 文档中锚的数目.  

 

二、方法 
1、write("string")      //将字符串突出给当前窗口.(字符串可以含有HTML标记) 

2、writeln("string")        //与write()类似,在结尾追加回车符,只在预定格式文本中生效.  

3、clear()              //清当前窗口.  

4、close()              //关闭当前窗口. 

5、open()                   //打开文档

一、Document子对象的接口

1、 anchors[]对象的一个集合,该对象代表文档中的锚

<a name="a1">1</a>

<a name="a2">2</a>

<a name="a3">3</a>

<a>4</a>

<a>5</a>

<script type="text/javascript">

function dwo(s){

    document.write(s+"<br>");

}

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

    dwo(document.anchors[i].name);

}

</script>

 

2、 applets[]:该对象代表文档中的java小程序.

3、  Forms[]:代表文档中的表单元素.

4、 Images[]:文档中的一个图片元素

<img src="images/job0.gif" width="267" height="161" />

<img src="images/job0.gif" width="267" height="161" />

<img src="images/job0.gif" width="267" height="161" />

<script type="text/javascript">

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

    document.images[i].style.filter="FlipV";

    void(0);

}

</script>

5、 Links[]文档中一个链接.

6、 Cookie允许javaScript程序读写HTTPcookie,

二、对话框

1、 alert()用于向用户显示消息.

2、 Confirm()要求用户点击ok或Cancel键来确认或者取消某个操作.

3、 Prompt()要求用户输入一个字符串[1].

四、状态栏

1、Window.status

    window.setInterval("window.status=new Date()",1000); void(0);

2、 window.defatltStatus()

五、表单和表单对象

1、forms[]集合可以找到一个或多个form对象,是按照在文档出现的顺序存放,forms[0]代表了文档是第一个表单

<form id="setForm" name="setForm" method="post" action="">

Document. setForm [document.setForm.length-1]:引用文档的最后一个表单.

2、elements[]集合:包含各种表单输入元素的JS对象,按照出现在form中的先后顺序存放在elements[]集合中.

Name:form的name值,       value:文字框内输入的文字   show(form)要加form

<form id="form1" name="form1" method="post" action="" onsubmit="show(this); return false;">

<input type="text" name="textfield2" id="textfield2" />

<input type="text" name="textfield" id="textfield" />

<input type="submit" name="button" id="button" value="提交" /></p>

</form>

<script type="text/javascript">

function show(form){

  var str = "";

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

      str += form.elements[i].name +"="+ form.elements[i].value + "<br>";

  }

  document.write(str);

}

</script>

 

六、多选框如果 chenecked = true;是选中状态

function checkReverse() {

  var hotId = document.getElementById("musce");

  var che = hotId.getElementsByTagName("input");

  for(var i=0; i<che.length-3; i++){

       if(che[i].checked){

            che[i].checked = false;

       }

       else {

            che[i].checked = true;

       }

  }

}

原文地址:https://www.cnblogs.com/couxiaozi1983/p/2389066.html