1.多加练习,多加思考
重点:给input添加编号
为什么不直接添加编号?
由于有些浏览器不支持直接在标签内部自定义属性,如果在标签中自定了属性,浏览器会无法识别此舒心,它会自己以为此属性无效.因此需要将编号添加在js代码中.
Input[i].index=i;
2.代码实现
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1 div {height:200px; width:200px; background:#999; border:1px solid red; display:none}
.color{background:#FF0;}
</style>
<script>
//加载HTML文件
window.onload=function()
{
//获取所有的input标签
var Input=document.getElementsByTagName('input');
//获取所有div
//无法获取:vat Divs=document.getElementsByTagName('div');
var Div1=document.getElementById('div1');
var Div=Div1.getElementsByTagName('div');
//input赋予点击事件
for(var i=0;i<Input.length;i++){
//给每一个input设置一个序号
Input[i].index=i;
Input[i].onclick=function()
{
for(var i=0;i<Input.length;i++)
{
//所有的颜色都变成无色
Input[i].className='';
//所有的div都不显示
Div[i].style.display='none';
}
//特别注意是当前点击事件
this.className='color';
//显示当前点击事件的div
//alert(this.index);
Div[this.index].style.display='block';
}
}
}
</script>
</head>
<body>
<div id=div1>
<input class="color" type="button" value="教育"/>
<input type="button" value="培训"/>
<input type="button" value="招生"/>
<input type="button" value="出国"/><br/>
<div style="display:block;">大家好</div>
<div>按时发答案是</div>
<div>按时gas大V</div>
<div>昂的说法</div>
</div>
</body>
</html>