[英]Saving and comparing table cell values
我正在創建一個簡單的內存匹配游戲,我想比較每個單擊的單元格的文本值以查看是否匹配。 底部的click事件處理程序是我這樣做的嘗試,但是我不確定如何保存被單擊的單元格。 如何保存每個單元格的文本值並進行比較,同時還保存要比較的單元格,以便在單擊的兩個單元格不相等時可以將其隱藏? 文字縮進設置為100%,默認情況下隱藏溢出。
var createTable = function (col, row) {
$('table').empty();
for (var i = 1; i <= row; i++) {
$('table').append($('<tr>'));
}
for (var j = 1; j <= col; j++) {
$('tr').append($('<td>'));
}
countCells = row * col;
};
createTable(4, 1);
var arr = [1, 2, 1, 2];
var pushNum = function () {
var len = arr.length;
for (var i = 0; i <= len; i++) {
var ran = Math.ceil(Math.random() * arr.length) - 1;
$('td').eq(i).append(arr[ran]);
arr.splice(ran, 1);
}
};
pushNum();
var match1;
$('td').click(function () {
$(this).css('text-indent', 0);
match1 = $(this).eq();
if (match1.val() === "1") {
alert("GOOD");
}
});
就個人而言,我認為我將創建幾個函數來處理兩件事:
1)每個單元格上的onclick
函數,當單擊某個單元格時,它們將簡單地切換某種“被單擊”類(使用toggleClass()
)。 它也可以具有視覺指示器(例如,更改文本或背景色或類似的顏色)。
2)切換完成后,一個獨立的函數將由#1中的“ onclick”調用,以檢查是否正好單擊了2個單元格。 您可以使用jQuery選擇器來獲取所有帶有“ clicked”類的單元格,並且,如果返回集的長度等於2,則可以使用first()
和last()
函數來獲取被單擊的單元格的值。您可以比較它們。 這是您從上面集成現有的“它們是否匹配” JS代碼的功能。
這樣,您實際上就不必存儲值,除非您知道自己做出了兩個選擇,然后您就可以實時檢查它們,所以您將永遠不會進行檢查。
發現它很有趣,所以我嘗試用簡單的jQuery實現它
var $mainTable = $('#mainTable'),
myWords = [],
valA, valB, col=4, row=3, start;
// function to create the table
var createTable = function (col, row) {
var $table = $('<table>'), i;
// construct our table internally
for(var i=0; i<row; i++){
var $tr = $('<tr data-row="'+i+'">'); // make row
for(var j=0; j<col; j++){
$tr.append($('<td data-col="'+j+'">')); // make cell
}
$table.append($tr);
}
$mainTable.html($table.html());
};
// generate an array random words from a dictionary
var giveWords = function(pairsRequested){
var dictionary = ['now','this','is','only','a','test','I','think'],
ar = dictionary.slice(0,pairsRequested);
ar = ar.concat(ar);
// taken from @ http://jsfromhell.com/array/shuffle [v1.0]
for(var j, x, i = ar.length; i; j = parseInt(Math.random() * i), x = ar[--i], ar[i] = ar[j], ar[j] = x);
return ar;
}
// initialize
createTable(col,row);
myWords = giveWords(6); // our words array
// listen
$mainTable.on('click', 'td' ,function(){
var $that = $(this),
thisCol = $that.data('col'),
thisRow = $that.closest('tr').data('row');
if(!valB && !$that.hasClass('clicked')){
var itemNum = (thisRow*(col))+thisCol;
if(!valA){ // first item clicked
valA = myWords[itemNum];
$that.addClass('clicked')
.text(valA);
} else { // we already have a clicked one
valB = myWords[itemNum];
if(valA === valB){ // if they match...
$mainTable.find('.clicked')
.add($that)
.removeClass('clicked')
.addClass('revealed')
.text(valA);
// check how many open remaining
var open = $mainTable.find('td')
.not('.revealed')
.length;
if(open===0){ // if 0, game over!
var elapsed = Date.now()-start;
alert('Congratulations! cleared the table in '+elapsed/1000+' seconds.');
}
valA = valB = undefined;
} else {
$that.addClass('clicked')
.text(valB);
setTimeout(function(){ // leave the value visible for a while
$mainTable.find('.clicked')
.removeClass('clicked')
.text('');
valA = valB = undefined;
},700);
}
}
}
if(!start){ // keep time of game completion
start=Date.now();
}
});
將data-num
屬性用於表單元格值,而不是使用類。 有一些問題需要解決,例如雙擊同一單元格或單擊已顯示的單元格,但總的來說,現在可以使用了!
var countCells;
var createTable = function (col, row) {
var str = '';
for (var i = 1; i <= row; i++) {
str += '<tr>';
for (var j = 1; j <= col; j++) {
str += '<td>';
}
str += '</tr>';
}
$('table').html(str);
countCells = row * col;
};
createTable(6, 3);
function shuffle(o) {
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i, 10), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
// http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
var arr = [];
for (var i = 0; i < countCells / 2; i++) {
arr[i] = arr[i + countCells / 2] = i + 1;
}
shuffle(arr);
//console.log(arr);
var tds = $('table td');
tds.each(function (i) {
this.setAttribute('data-num', arr[i]);
});
var attempts = 0;
var match1 = null;
var info = $('#info');
var wait = false;
$('td').click(function () {
if (wait) {
return;
} // wait until setTimeout executes
var num = this.getAttribute('data-num');
if (match1 === null && num != 'X') { //1st click on unmatched cell
match1 = this;
this.innerHTML = num;
attempts++;
info.text('Attempts: ' + attempts);
return;
} else { //2nd click
var num1 = match1.getAttribute('data-num'); //1st num
if (match1 === this) {
// clicked twice this cell
return;
} else if (num == 'X') {
// clicked on already revealed cell
return;
} else if (num == num1) {
// both cells match
info.text('Bingo! Attempts: ' + attempts);
this.innerHTML = match1.innerHTML = num1;
this.setAttribute('data-num', 'X');
match1.setAttribute('data-num', 'X');
match1 = null;
} else {
// cells not match
info.text('Try again. Attempts: ' + attempts);
this.innerHTML = num;
var self = this;
wait = true;
window.setTimeout(function () {
self.innerHTML = match1.innerHTML = '';
match1 = null;
wait = false;
}, 1000);
}
}
});
請享用! :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.