[英]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.