

另一種寫法:

<!DOCTYPE?html>
<html?lang="en">
<head>
????<meta?charset="UTF-8">
????<meta?name="viewport"?content="width=device-width,?initial-scale=1.0">
????<meta?http-equiv="X-UA-Compatible"?content="ie=edge">
????<title>Document</title>
</head>
<body>
<button>按鈕1</button>
<button>按鈕2</button>
<button>按鈕3</button>???
<script>
????匿名函數(shù)自執(zhí)行
????簡寫1:(函數(shù))();
(function(b){
????var?btns?=?document.querySelectorAll("button");
????console.log(b);
})(10);
/*
????全局污染:?不要使用全局變量,寫在fn自執(zhí)行里,也叫聲明一個命名空間
????var?tab?=?.....;
????var?tab?=?.....;??????覆蓋之前聲明
*/
(function(){?//?聲明一個命名空間
????var?btns?=?document.querySelectorAll("button");
????//?for(var?i?=?0;?i?<?btns.length;?i++){
????//?????btns[i].index?=?i;
????//?????btns[i].onclick?=?function(){
????//?????????console.log(this.index);
????//?????};
????//?}
????function?fn(index){
????????btns[index].onclick?=?function(){
????????????console.log(index);
????????};
????}
????for(var?i?=?0;?i?<?btns.length;?i++){
????????fn(i);
????}
????//?fn(0);
????//?fn(1);
????//?fn(2);
????//?fn(...100+);
})();???
</script>????
</body>
</html>