前端 JS基礎理論總結(九)
阿新 • • 發佈:2019-01-13
閉包存迴圈的索引值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>閉包存迴圈的索引值</title> <style type="text/css"> li{ height: 30px; background-color: gold; margin-bottom: 10px; } </style> <script type="text/javascript"> //閉包的用途:存迴圈的索引值 window.onload = function(){ var aLi = document.getElementsByTagName('li'); // alert(aLi.length);//8 for(var i=0; i<aLi.length; i++){ /* aLi[i].onclick = function(){ alert(i);//每個li都彈出8,因為點選時迴圈已完畢,i最後為8 } */ (function(k){//這裡的k是形參 aLi[k].onclick = function(){ alert(k);//彈出每個li的索引值 } })(i);//這裡的i是實參 } } </script> </head> <body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> </ul> </body> </html>
閉包做私有變數計算器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>閉包做私有變數計數器</title> <script type="text/javascript"> //閉包的用途:私有變數計數器 var count = (function(){ var a = 0; function bb(){ a++; return a; } return bb; })(); //每呼叫一次count,a就自增一次 alert(count());//1 alert(count());//2 var c = count(); alert(c);//3 </script> </head> <body> </body> </html>
獲取位址列引數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>獲取位址列引數</title> <script type="text/javascript"> window.onload = function(){ //url?aa=tom#12 var data = window.location.search;//?aa=tom var hash = window.location.hash;//#12 alert(hash);//#12 var oSpan = document.getElementById('span01'); // alert(data);//?aa=tom var arr = data.split('='); // alert(arr);//?aa,tom var name = arr[1]; oSpan.innerHTML = name; } </script> </head> <body> <div>歡迎<span id="span01"></span>訪問我的主頁</div> </body> </html>
Math
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Math</title>
<script type="text/javascript">
// var num = Math.random();
// alert(num);//彈出0-1之間的隨機數
var a = 10;
var b = 20;
// var num = Math.random()*(b-a)+a;
// alert(num);//彈出10-20之間的隨機數
var arr = [];
for(var i=0; i<20; i++){
// var num = Math.floor(Math.random()*(b-a)+a);//向下取整,10-19
var num = Math.floor(Math.random()*(b-a + 1)+a);//向下取整,10-20
arr.push(num);//生成一個數就放進陣列
}
alert(arr);//17,20,20,11,11,19,17,16,10,11,16,11,18,13,13,11,17,14,19,19
</script>
</head>
<body>
</body>
</html>