1.封闭函数

封闭函数是JavaScript中匿名函数的另外一种写法,创建一个一开始就执行而不用命名的函数

/在封闭函数前加’;‘,可以避免js压缩时出错/
;(function(){

alert('hello world!');})();/*当i大于78时等于78,小于时等于89*/var i = 90>78?78:89;alert(i);/*第二个写法*/!function(){ alert('hello world!');}();/*第三个写法*/~function(){ alert('hello world!');}();**2.常用内置对象**

1.document

document.getElementById 通过id获取元素

document.getElementByTagName 通过标签名获取元素

document.referrer 获取上一个跳转页面的地址(需要服务器环境)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>内置对象</title>
<script type="text/javascript">
window.onload = function(){

/*存储上一个地址,需要服务器环境*/ /*var sUrl = document.referrer;*/ var oBtn = document.getElementById('btn01'); oBtn.onclick = function(){ /*window.location.href = sUrl;*/ window.location.href = 'http://www.baidu.com'; }}</script>

</head>

<body>

<input type="button" name="" value="跳转" id="btn01">

</body>
</html>

2.location

window.location.href 获取或者重定向url地址

window.location.search 获取地址参数部分

window.location.hash 获取页面锚点或者叫哈希值

例子:通过地址参数更换背景

文件一:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>内置对象</title>
<script type="text/javascript">
window.onload = function(){

var oBody = document.getElementById('body01'); /*通过?...传递地址*/ var sDate = window.location.search; /*通过#...传递地址*/ var sHash = window.location.hash; /*alert(sHash);*/ if(sDate != ''){ var iRan = sDate.split('='); /*以等号分割*/ var iNum = iRan[1]; /*元素集的第二个*/ if(iNum==1){ oBody.style.backgroundColor = 'gold'; } else if(iNum==2){ oBody.style.backgroundColor = 'red'; } else if(iNum==3){ oBody.style.backgroundColor = 'blue'; } }}</script>

</head>

<body id="body01">

<a href="inner01.html">到inner01</a>

</body>
</html>

文件二:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>设置背景</title>
</head>

<body>

<a href="innerobject.html?a=1#123">背景一</a><br /><br /><a href="innerobject.html?a=2">背景二</a><br /><br /><a href="innerobject.html?a=3">背景三</a>

</body>
</html>

3.Math

Math.random 获取0-1的随机数

Math.floor 向下取数

Math.ceil 向上取数

例子:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>math</title>
<script type="text/javascript">

var iNum = Math.PI;alert(iNum);var iNum01 = [];for(var i=0;i<20;i++){ /*返回0-1的随机数*/ iNum02 = Math.random(); iNum01.push(iNum02); }alert(iNum01);/*向下取整*/alert(Math.floor(5.7));/*向上取整*/alert(Math.ceil(8.1));/*产生10-20的随机数*/var iNum03 = 10;var iNum04 = 20;var iNum05 = [];for(var i=0;i<20;i++){ /*因为向下取整,为了出现20,加1,*/ var iN = Math.floor((iNum04-iNum03+1)*Math.random()) + iNum03; iNum05.push(iN);}console.log(iNum05); /*在浏览器console里显示*/</script>

</head>

<body>
</body>
</html>

4.js调试方法

(1)alert():会阻止程序的运行

(2)console.log():浏览器console

(3)document.title():页面标题