<script type="text/javascript">
varbtn=document.getElementsByTagName_r('button');
varmyA=document.getElementsByTagName_r('a');
varmySpan=document.getElementsByTagName_r('span');
varmyBody=document.getElementsByTagName_r('body');
vara_arr=['red','green','black'];
varbody_arr=['pink','#a3c5a8','gray'];
window.onload=function() {
for(varj=0;j<myA.length;j++) {
myA[j].style.backgroundColor=a_arr[1];
}
myBody[0].style.backgroundColor=body_arr[1];
mySpan[1].style.background='white';
}
for(vari=0; i<a_arr.length;i++) {
console.log(a_arr[i]);
btn[i].index=i;
btn[i].onclick=function() {
console.log(1);
console.log(a_arr[i]);
for(varj=0;j<myA.length;j++) {
myA[j].style.backgroundColor=a_arr[this.index];
}
myBody[0].style.backgroundColor=body_arr[this.index];
mySpan[this.index].style.backgroundColor='white';
if(this.index==0) {
mySpan[this.index+1].style.backgroundColor='transparent';
mySpan[this.index+2].style.backgroundColor='transparent';
}
if(this.index==1){
mySpan[this.index-1].style.backgroundColor='transparent';
mySpan[this.index+1].style.backgroundColor='transparent';
}
if(this.index==2){
mySpan[this.index-1].style.backgroundColor='transparent';
mySpan[this.index-2].style.backgroundColor='transparent';
}
console.log(this.index);
console.log(this.index-1);
console.log(this.index+1);
}
}
script>
如上段代碼所示,相信如果看的話都能看懂。所以在此我就簡(jiǎn)單的說一下窿冯,我之前在寫這段代碼的時(shí)候遇到的問題。
1牲芋、正如您所看到的第一個(gè)加粗變大呈紅色的代碼:btn[i].index=i;我之前寫的時(shí)候沒有加這句話冯遂,而且在a_arr數(shù)組里面添加的也不是,而是i膘茎,但是造成的結(jié)果是出不來我想要的結(jié)果薪夕,而且如果在控制臺(tái)把a(bǔ)_arr[i]打印出來的話脚草,結(jié)果會(huì)顯示說a_arr[i]未定義。原因很簡(jiǎn)單 因?yàn)镴S是一種解釋性的腳本語言原献,只有當(dāng)用戶需要的時(shí)候馏慨,才會(huì)解釋其相對(duì)應(yīng)的代碼。而且我之前的那段代碼是寫在btn的點(diǎn)擊事件里面姑隅,所以只有當(dāng)用戶點(diǎn)擊按鈕的時(shí)候才會(huì)執(zhí)行里面的代碼写隶,而此時(shí)頁面中的i已經(jīng)結(jié)束的它自身的循環(huán),即i的值為3讲仰;當(dāng)我們點(diǎn)擊的時(shí)候a_arr[3],很顯然在數(shù)組a_arr[]里面沒有這個(gè)值樟澜,所以在控制臺(tái)才會(huì)出現(xiàn)undefined。
2叮盘、把代碼寫成上述的好處:在點(diǎn)擊之前 利用for循環(huán),將i的值付給每個(gè)btn[i]的下標(biāo) 即btn[i].index霹俺。
我們都知道下標(biāo)都是從0開始柔吼,所以btn[i].index也就對(duì)應(yīng)著每一個(gè)i的值。當(dāng)鼠標(biāo)點(diǎn)擊按鈕的時(shí)候丙唧,this.index就相當(dāng)于btn[i].index的值愈魏,(this指代當(dāng)前對(duì)象的所有者),也就是點(diǎn)擊按鈕的那個(gè)下標(biāo)想际。然后將這一點(diǎn)的下標(biāo)值傳送到a_arr[]數(shù)組里面培漏。即可得到我們想要的結(jié)果