<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>选项卡</title>
<style type="text/css">
div{
width: 210px;
height: 210px;
background: #CCC;
}
.liang{background: yellow;}
</style>
<script type="text/javascript">
var arr=["李","明","最","帅!"];
var i=0;
var temp='';
var oBtn=document.getElementsByTagName('input');
function show(){//制作定时器执行的函数
var oDiv=document.getElementById('div1');
for (var j=0;j<oBtn.length;j++)
{
oBtn[j].className='';
};
oBtn[i].className='liang';
oDiv.innerHTML=arr[i++];
if(i==oBtn.length)
i=0;
};
window.onload=function(){ //把这句放在最前面,却会错,为什么
var oDiv=document.getElementById('div1');
for (var i=0;i<oBtn.length;i++)
{
oBtn[i].index=i;
oBtn[i].onmouseover=function (){
clearInterval(temp);
for (var j=0;j<oBtn.length;j++)
{
oBtn[j].className='';
}
this.className='liang';
oDiv.innerHTML=arr[this.index];
}
oBtn[i].onmouseout=function(){
temp=setInterval(show,1000);
}
};
clearInterval(temp);//调用之前先关掉,否则累加
temp=setInterval(show,1000);
show();
};
</script>
</head>
<body>
<input type="button" id="" value="按钮1" />
<input type="button" id="" value="按钮2" />
<input type="button" id="" value="按钮3" />
<input type="button" id="" value="按钮4" />
<div id="div1">李</div>
</body>
</html>
把window.onload放在最前面,却会错,为什么
<html>
<head>
<meta charset="UTF-8">
<title>选项卡</title>
<style type="text/css">
div{
width: 210px;
height: 210px;
background: #CCC;
}
.liang{background: yellow;}
</style>
<script type="text/javascript">
var arr=["李","明","最","帅!"];
var i=0;
var temp='';
var oBtn=document.getElementsByTagName('input');
function show(){//制作定时器执行的函数
var oDiv=document.getElementById('div1');
for (var j=0;j<oBtn.length;j++)
{
oBtn[j].className='';
};
oBtn[i].className='liang';
oDiv.innerHTML=arr[i++];
if(i==oBtn.length)
i=0;
};
window.onload=function(){ //把这句放在最前面,却会错,为什么
var oDiv=document.getElementById('div1');
for (var i=0;i<oBtn.length;i++)
{
oBtn[i].index=i;
oBtn[i].onmouseover=function (){
clearInterval(temp);
for (var j=0;j<oBtn.length;j++)
{
oBtn[j].className='';
}
this.className='liang';
oDiv.innerHTML=arr[this.index];
}
oBtn[i].onmouseout=function(){
temp=setInterval(show,1000);
}
};
clearInterval(temp);//调用之前先关掉,否则累加
temp=setInterval(show,1000);
show();
};
</script>
</head>
<body>
<input type="button" id="" value="按钮1" />
<input type="button" id="" value="按钮2" />
<input type="button" id="" value="按钮3" />
<input type="button" id="" value="按钮4" />
<div id="div1">李</div>
</body>
</html>
把window.onload放在最前面,却会错,为什么
一开始var i=0;定义的i变量就和后面循环中的i变量处于同一函数中了,被认作同一个变量,冲突了
代码简化一下好理解
var i = 0;//这个i是全局变量
setTimeout(function () {
alert(i);//输出全局变量i的值:0
}, 2000);window.onload = function () {
for (var i = 0; i < 4; i++) {//这个i是局部变量,与上边的i不是同一个变量
}
//循环之后局部变量i的值是4,但全局变量i的值还是0
}----------------------------------------------
把window.onload放在最前面window.onload = function () {
var i = 0;//这个i就也是局部变量了
setTimeout(function () {
alert(i);//输出变量i的值:4
}, 2000); for (var i = 0; i < 4; i++) {//这个i与上边的i都是同一个函数中的局部变量,是同一个变量
}
//循环之后i的值是4
}