一贰军、封閉函數(shù)
-
1.1植兰、封閉函數(shù)定義:javascript中匿名函數(shù)的另外一種寫法份帐,創(chuàng)建一個一開始就執(zhí)行而不用命名的函數(shù)
-
一般定義的函數(shù)和執(zhí)行函數(shù):
function myalert(){ alert('hello!'); }; myalert();
-
封閉函數(shù)寫法一:去掉函數(shù)名字,用括號抱起來楣导,加上小括號執(zhí)行
(function myalert(){ alert('hello!'); })();
-
封閉函數(shù)寫法二:可以在函數(shù)定義前加上
“~”
和“!”
等符號來定義匿名函數(shù)!function myalert(){ alert('hello!'); }()
或者
~function myalert(){ alert('hello!'); }()
-
-
1.2废境、封閉函數(shù)的好處:封閉函數(shù)可以創(chuàng)造一個獨立的空間,在封閉函數(shù)內(nèi)定義的變量和函數(shù)不會影響外部同名的函數(shù)和變量筒繁,可以避免命名沖突噩凹,在頁面上引入多個js文件時,用這種方式添加js文件比較安全毡咏,比如:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>封閉函數(shù)的好處</title> <script type="text/javascript"> var iNum1 = 10; function myalter() { alert('hello'); } ~function () { var iNum1 = 20; function myalter() { alert('hello world!'); } alert(iNum1); myalter(); }(); alert(iNum1); myalter(); </script> </head> <body> </body> </html>
提示:我們可以看到封閉函數(shù)里面的函數(shù)
myalter
并不會把封閉函數(shù)外的函數(shù)myalter
給屏蔽掉
二驮宴、常用內(nèi)置對象
-
2.1、document
-
通過
id
獲取元素document.getElementById
-
通過
標簽名
獲取元素document.getElementsByTagName
-
獲取
上一個跳轉(zhuǎn)頁面的地址
(需要服務(wù)器環(huán)境)document.referrer
-
-
2.2呕缭、location
-
獲取或者重定url地址
window.location.href
-
獲取地址參數(shù)部分
window.location.search
如下例子:
<script type="text/javascript"> window.onload = function () { // 根據(jù)id獲取一個按鈕的標簽 var oButton = document.getElementById('button1'); var aData = window.location.search; if (aData != ''){ alert(aData.split('=')); } } </script>
-
獲取頁面錨點或者叫哈希值
window.location.hash
-
-
2.3堵泽、Math 對象
-
Math.random
之能獲取0-1的隨機數(shù),不包括 1alert(Math.random());
-
Math.floor
向下取整: 結(jié)果是:3alert(Math.floor(3.4));
-
Math.ceil
向上取整: 結(jié)果是:4alert(Math.ceil(3.4));
提示:向上或者向下取值是
沒有四舍五入
的
-
-
2.4恢总、舉例:生成 10-20之間的隨機數(shù)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>生成10到20的隨機數(shù)</title> <script type="text/javascript"> var iNum1 = 10; var iNum2 = 20; var array2 = []; for(var i=0;i<20;i++){ // 生成10-20之間的隨機數(shù) var iNum02 = Math.floor((iNum2-iNum1+1)*Math.random()) + iNum1; array2.push(iNum02); } console.log(array2); </script> </head> <body> </body> </html>
打印結(jié)果: 15迎罗、20、11片仿、16纹安、18、20砂豌、20厢岂、20、18奸鸯、16咪笑、17、20娄涩、12窗怒、14、13蓄拣、11扬虚、17、17球恤、17辜昵、13
三、調(diào)試 js
的方法
-
3.1咽斧、alter 調(diào)試比較直觀
var iNum1 = 10; alert(iNum1);
-
3.2堪置、console.log 在數(shù)據(jù)較多的時候可以直接展示出來躬存,打印出來查看比較方便,比如上面的打印一個數(shù)組
console.log(array2);
-
3.3舀锨、document.tittle 可以直接顯示在網(wǎng)頁的標題上岭洲,如下
document.title = "測試";