JS添加事件
方法1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="button" name="btn1" id="btn1" value="按钮" />
<script type="text/javascript">
var oBtn=document.getElementById('btn1');
// function test(){
// alert("test");
// }
// oBtn.onclick=test;
oBtn.onclick=function (){
alert("test");
};
</script>
</body>
</html>
方法2
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
//需要添加window.onload
//否则<input/>还没有加载,就先加载事件了,出错
window.onload=function (){
var oBtn=document.getElementById('btn1');
oBtn.onclick=function() {
alert("test");
};
}
</script>
</head>
<body>
<input type="button" name="btn1" id="btn1" value="按钮" />
</body>
</html>
获取一组元素
getElementsByTagName()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
div {
width: 200px;
height: 200px;
float: left;
border: 1px solid black;
margin: 10px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var aDiv=document.getElementsByTagName('div');
for(var i=0;i<aDiv.length;i++){
aDiv[i].style.background='red';
}
}
</script>
</head>
<body>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
</body>
</html>
全选不选反选示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
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(){
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++) {
if(aCh[i].checked==true){
aCh[i].checked=false;
}else{
aCh[i].checked=true;
}
}
}
}
</script>
</head>
<body>
<input type="button" name="" id="btn1" value="全选" />
<input type="button" name="" id="btn2" value="不选" />
<input type="button" name="" id="btn3" value="反选" /><br/>
<div id="div1">
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
<input type="checkbox" name="" id="" value="" /> <br/>
</div>
</body>
</html>