提取事件
为元素添加事件——DOM 0级的事件绑定方式*
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input id="btn1" type="button" value="按钮">
<script>
var oBtn = document.getElementById('btn1');
function abc(){
alert("a");
}
oBtn.onclick = abc; //a;
</script>
</body>
</html>
匿名函数:
var oBtn = document.getElementById('btn1');
oBtn.onclick = function (){
alert("a");
}
window.onload
页面加载之后完成——解决js加载顺序问题
行为、样式、结构三者分离;
window.onload=function (){
var oBtn = document.getElementById('btn1');
oBtn.onclick = function (){
alert("a");
};
};
getElementsByTagName——获取一组元素
数组的使用:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
float: left;
border:1px solid black;
margin:10px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
window.onload = function (){
var aDiv = document.getElementsByTagName('div');
//所有div都变green,数组循环
//
//方法一:
aDiv[0].style.backgroundColor = 'red';
aDiv[1].style.backgroundColor = 'red';
aDiv[2].style.backgroundColor = 'red';
aDiv[3].style.backgroundColor = 'red';
// 方法二:
for(var i = 0; i < aDiv.length;; i++){
aDiv[i].style.backgroundColor = 'red';
}
}
</script>
</body>
</html>
循环
while循环
var i = 0; //1.初始化
while(i < 5){ //2.条件
console.log(i); //3.语句
i++; //4.自增
}
for循环
for(初始化;条件;自增){
语句;
}
全选、不选、反选功能
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<input id="btn1" type="button" value="全选"><br>
<input id="btn2" type="button" value="不选"><br>
<input id="btn3" type="button" value="反选"><br>
<div id="div1">
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
<input type="checkbox"><br>
</div>
<script>
window.onload = function(){
var oBtn1 = document.getElementById('btn1');
var oBtn2 = document.getElementById('btn2');
var oBtn3 = document.getElementById('btn3');
var oDiv = document.getElementById('div1');
var aCh = oDiv.getElementsByTagName('input');
//全选
oBtn1.onclick = function (){
// aCh[0].checked = true;
for(var i = 0; i < aCh.length; i++){
aCh[i].checked = true;
}
}
// 不选
oBtn2.onclick = function (){
for(var i = 0; i < aCh.length; i++){
aCh[i].checked = false;
}
}
// 反选
oBtn3.onclick = function (){
for(var i = 0; i < aCh.length; i++){
// var toCh = aCh[i].checked;
if(aCh[i].checked == true){
aCh[i].checked = false;
}else{
aCh[i].checked = true;
}
}
}
};
</script>
</body>
</html>