js基礎【開關思想】

<!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>

<div>box</div>

<div>box</div>

<div>box</div>

 

<script>

var aDiv = document.getElementsByTagName('div');

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

aDiv[i].flag = 0; //給每一個標籤添加一個flag標記點擊狀態 0 代表首次點擊 1代表第二次點擊

aDiv[i].onclick = function(){

if(this.flag == 0){

this.style.backgroundColor = "red";

this.flag = 1;

}else{

this.style.backgroundColor = "yellow";

this.flag = 0;

}

}

}

</script>

</body>

</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章