我試圖讓一個數字小鍵盤從0到9,當某些數字按特定的順序被按下會發生。使JavaScript檢測按鈕被按下在一定的順序
因此,像這樣
if (button1 gets pressed then button2 then button3)
alert('You did the code!')
}
else {
alert('You did not do the code')
}
沒有jQuery
請
謝謝!
我試圖讓一個數字小鍵盤從0到9,當某些數字按特定的順序被按下會發生。使JavaScript檢測按鈕被按下在一定的順序
因此,像這樣
if (button1 gets pressed then button2 then button3)
alert('You did the code!')
}
else {
alert('You did not do the code')
}
沒有jQuery
請
謝謝!
//sequence is 358
//SOLUTION
sequence = {
check : function(e){
sequence.value += this.textContent;
if (sequence.value == sequence.sequence)
{
alert(1);
sequence.value = "";
}
else
{
if (sequence.timer)
{
clearTimeout(sequence.timer);
}
sequence.timer = setTimeout("sequence.value=''", 1000);
}
},
value : "",
sequence : "358"
}
//THIS CODE ATTACHES CLICK HANDLERS TO THE BUTTON, NOT PART OF THE SOLUTION
Array.prototype.map.call(document.querySelectorAll("button"), function(element){
element.addEventListener("click", sequence.check, false);
});
//end
<button>7</button><button>8</button><button>9</button><br/>
<button>4</button><button>5</button><button>6</button><br/>
<button>1</button><button>2</button><button>3</button><br/>
<button>0</button>
這是如何工作的一定的時間間隔後清零陣列。我不想用數值污染全局範圍,所以我用一個對象來存儲變量和check
方法。
該對象被稱爲sequence
。
它有三個屬性
check
,它檢查輸入一個按鈕被點擊時的方法。value
,它保存序列值直到找到正確的序列。sequence
,該屬性保持正確的值。
頁面上的每個按鈕都分配有點擊處理程序。點擊後會觸發sequence.check
。通過this
關鍵字(指按鈕)我們提取數字(通過textContent
)。我們將該數字添加到值字符串中。然後我們檢查值是否與序列匹配。如果這樣執行一些代碼(在這種情況下是一個警報)並重置該值。有一個定時器組。如果用戶在一秒鐘內沒有輸入新號碼,則定時器將重置value
。 setTimeout
這樣做。 1000
代表1000 milliseconds = 1 second
。
我會通過監視事件來實現這一點,如果密鑰是數字,則將其添加到數組中。同時,檢查數組內容以查看它們是否處於特定的定義順序。如果是的話,如果沒有的話,發起你需要做的任何事情,除了向陣列添加密鑰外什麼也不做。一旦你的序列完成,清除數組,讓一個新的序列。
你可以得到併發之類的東西,沒有完成序列等
數組比一個字符串更高效嗎?如果是這樣,你如何檢查數組中的值的順序? – SRing 2015-02-11 18:58:00
嗯好問題。我猜想,如果它是簡單的,用戶需要輸入'1 2 3 4 5 6'來發生某些事情,那麼你可以測試這些字符串。 – 2015-02-11 19:00:42
對於此操作,數組和字符串將具有相同的效率,差異是意圖。如果在按下按鈕時追加到字符串,那麼您只是針對表示正確順序的模式(如var pressed =「1 | 3 | 2 | 4 |」,有效=(按下===「 1 | 2 | 3 | 4 |「);'在這種情況下,valid將等於'false'。如果你對數組做了這樣的操作,你必須迭代數組來測試它們是否相等 – 2015-02-11 19:17:04
下面是一個簡單的系統,做的你在找什麼部分:
var buttons = document.querySelectorAll('button'),
i;
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
var pressed = document.getElementById('pressed');
pressed.value += this.value + "|";
if (pressed.value === '1|2|3|') {
alert('You unlocked it!');
}
if (pressed.value.length >= 6) {
//Start over
pressed.value = "";
}
}, false);
}
<input id='pressed' type='text' />
<button value='1'>One</button>
<button value='2'>Two</button>
<button value='3'>Three</button>
或者如果你真的想變得很花哨,下面是一個使用'data'屬性來存儲有效組合http:// jsfiddle.net/s9v9mn4c/ – 2015-02-11 19:28:33
您需要存儲的順序,或添加到一個櫃檯。 – Mouser 2015-02-11 18:49:29
閱讀狀態機,繪製流程圖,狀態圖,很有趣! – MatthewG 2015-02-11 18:51:50