第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

js中鍵盤事件

?document.onkeydown = function (event) {

? ? ? ?

? ? ? ? event = event || window.event;

? ? ? ? p = as.length;//p=5

? ? ? ? if (event.keyCode == 40) {//向下鍵

? ? ? ? ? ? event.preventDefault ? event.preventDefault() : event.returnValue = false;

? ? ? ? ? ? index++;

? ? ? ? ? ? as[index].style.background = 'gray';

? ? ? ? ? ? as[index - 1].style.background = 'white';

? ? ? ? ? ? if (index > as.length - 1) {

? ? ? ? ? ? ? ? index = 0;

? ? ? ? ? ? ? ? ?as[index].style.backgroundColor = "gray";

? ? ? ? ? ? }

? ? ? ? ? ?

? ? ? ? }

????http://img1.sycdn.imooc.com//57a087490001481502440184.jpg為什么用向下鍵到最后一行的時(shí)候回不到一個(gè)行了?我明明設(shè)置好了 index到as.length的時(shí)候就令inde=0;為什么執(zhí)行的時(shí)候不可以?

正在回答

2 回答

我在你的代碼中添加了console.log(index);

http://img1.sycdn.imooc.com//57a1bfa70001380805120322.jpg

http://img1.sycdn.imooc.com//57a1bfe7000190aa06010199.jpg

控制臺(tái)爆出錯(cuò)誤(后面部分沒(méi)有截?。?。我不清楚你的index的初始值是為0還是-1,根據(jù)你的代碼來(lái)看,應(yīng)該是從-1開(kāi)始,那么第一個(gè)TypeError錯(cuò)誤是因?yàn)椤词棺铋_(kāi)始index++(index = 0),但是as[index - 1]也就是as[-1]不存在。第二個(gè)TypeError同樣如此,根據(jù)你所寫的代碼,as.length = 5,換言之 if(index > 4)才會(huì)執(zhí)行if內(nèi)部的代碼。假設(shè)此刻index為4,if判斷為false,按下down鍵,

index++ ?——>index = 5

as[index].style.background = "gray" ——>相當(dāng)于as[5].style.background = "gray"

然而問(wèn)題就在于這,數(shù)組的下標(biāo)越界,因此一直卡在這里,無(wú)法執(zhí)行下面的代碼,因此if條件內(nèi)部的代碼無(wú)法生效,所以向下鍵到最后一行的時(shí)候回不到第一行。

稍微修改了下你的代碼,在我的瀏覽器上測(cè)試成功了。

document.onkeydown = function (event) {
? ?event = event || window.event;
? ?p = as.length;
? ?if (event.keyCode == 40) {
? ? ? ?event.preventDefault ? event.preventDefault() : event.returnValue = false;
? ? ? ?if(index == -1)
? ? ? ?{
? ? ? ? ? ?as[p - 1].style.backgroundColor = "white";
? ? ? ?}
? ? ? ?index++;
? ? ? ?as[index].style.background = 'gray';
? ? ? ?as[index - 1].style.background = 'white';
? ? ? ?if (index == as.length - 1) {
? ? ? ? ? ?as[index - 1].style.backgroundColor = "white";
? ? ? ? ? ?as[index].style.backgroundColor = "gray";
? ? ? ? ? ?index = -1;
? ? ? ?}
? ? ? ?console.log(index)
? ?}
};

不過(guò)這樣寫總覺(jué)得邏輯上有些混亂,但是改動(dòng)不大,樓主理解應(yīng)該也比較容易。

2 回復(fù) 有任何疑惑可以回復(fù)我~

if (index > as.length - 1) 提前到as[index].style.background = 'gray'前面試試,會(huì)不會(huì)是as[index]中的index大于了as.length導(dǎo)致的?比如6的時(shí)候

0 回復(fù) 有任何疑惑可以回復(fù)我~

舉報(bào)

0/150
提交
取消
DOM事件探秘
  • 參與學(xué)習(xí)       99532    人
  • 解答問(wèn)題       1291    個(gè)

DOM事件?本課程會(huì)通過(guò)實(shí)例來(lái)給小伙伴們講解如何使用這些事件

進(jìn)入課程
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)