iT邦幫忙

0

網站彩蛋:程式碼出錯

請問各位大大,
我最近正在學做類似這位大大的網站彩蛋程式碼
(https://ithelp.ithome.com.tw/articles/10243349) ),
目標是讓用戶輸入的文字跟我指定的指令串一樣時,開啟IT邦幫忙的網站,
我打好了程式碼,但程式碼卻無法執行,輸入了指令串後頁面仍停在一樣的位置,
我檢查了很多遍都沒錯呀?
而且如果把這位大大的js程式碼整個貼上去,是會成功載入另一個頁面的,
請各位大大幫忙!

我的HTML程式碼:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="egg.js"></script>
    </head>
    <body>
        
    </body>
</html>

我的JS程式碼:

let secretCode = [79,75,73];
//宣告一個含有指令串keyCode的陣列
let userInput = [];   //宣告一個可接收用戶輸入的keyCode的空陣列
window.addEventListener('keyup',function(e){
    userInput.push(e.keyCode);
    userInput.splice(-secretCode.length - 1, userInput.length - secretCode.length);
});
//userInput.splice( 起始值 / 新增keyCode的放置位置,  );
if(userInput.join() === secretCode.join()){
    location.href = 'https://ithelp.ithome.com.tw/questions'
};
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
淺水員
iT邦大師 6 級 ‧ 2021-08-24 23:42:39

if 的位置應該要放在事件處理函式裡面,如下

let secretCode = [79, 75, 73];
let userInput = [];
window.addEventListener('keyup', function (e) {
    userInput.push(e.keyCode);
    userInput.splice(-secretCode.length - 1, userInput.length - secretCode.length);
    //應該把 if 挪到這裡面
    if (userInput.join() === secretCode.join()) {
        location.href = 'https://ithelp.ithome.com.tw/questions'
    };
});

另外,根據 MDN 的文件

Warning: This attribute is deprecated; you should use KeyboardEvent.key instead, if available.

keyCode 已經不建議使用,可以用 key 代替處理

let secretCode = 'OKI';
let userInput = '';
window.addEventListener('keyup', function (e) {
    //這邊改用 e.key 處理
    userInput = (userInput + e.key).slice(-3);
    if (userInput === secretCode) {
        location.href = 'https://ithelp.ithome.com.tw/questions'
    };
});

我要發表回答

立即登入回答