保存和比较表格单元格值

时间:2013-06-24 18:59:00

标签: javascript jquery dom text-comparison

我正在创建一个简单的内存匹配游戏,我想比较每个单击的单元格的文本值,看看是否匹配。底部的点击事件处理程序是我尝试这样做但我不确定如何保存单击哪个单元格。如何保存每个单元格的文本值并进行比较,同时还保存我正在比较的单元格,这样如果单击的两个单元格不相等,我可以隐藏它? Text-indent设置为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");
    }
});

3 个答案:

答案 0 :(得分:2)

就个人而言,我认为我会创建一些函数来处理两件事:

1)每个单元格上的onclick函数,当单击一个单元格时,只需切换某种“点击”类(使用toggleClass())。它也可以有一个视觉指示器(例如,更改文本或背景颜色或类似的东西)。

2)一个独立的函数,在切换完成后由#1中的“onclick”调用,以检查是否已经点击了2个单元格。您可以使用jQuery选择器来获取具有“clicked”类的所有单元格,如果返回集的长度等于2,则使用first()last()函数来获取值单击的单元格,以便您可以比较它们。这是您将从上面集成现有的“匹配”JS代码的功能。

这样,你实际上不需要存储该值,除非你知道你做了两个选择然后你会实时检查它们,否则你不会检查它。

答案 1 :(得分:2)

发现它很有趣所以我试图用简单的jQuery实现它

jQuery memory game

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(); 
    }
});

答案 2 :(得分:0)

对表格单元格值使用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);
        }
    }
});

jsfiddle

享受! : - )