Javascript JQuery存储数据以供以后检查

Javascript JQuery存储数据以供以后检查,javascript,jquery,Javascript,Jquery,类别。单元格是tic tac趾板表格中的9个单元格。单击X和O一直在工作,但我正在尝试检查并仅允许在单元格尚未使用时单击X和O 我尝试过使用JQuery数据属性,使用一个键和一个值,并且只使用一个值 $('.cell').on('click', function () { if (currentTurn === 'X' && (!$(this).data('already-played', 'yes'))) { $(this).text('X') $(this).data

类别。单元格是tic tac趾板表格中的9个单元格。单击X和O一直在工作,但我正在尝试检查并仅允许在单元格尚未使用时单击X和O

我尝试过使用JQuery数据属性,使用一个键和一个值,并且只使用一个值

$('.cell').on('click', function () {
if (currentTurn === 'X' && (!$(this).data('already-played', 'yes'))) {
  $(this).text('X')
  $(this).data('already-played', 'yes')
  currentTurn = 'O'
} else {
  $(this).text('O')
  $(this).data('already-played', 'yes')
  currentTurn = 'X'
}
数据属性是否适用于类似的情况,或者是否有人可以指出如何调整它

您应该替换:

!$(this).data('already-played', 'yes')
作者:

因为当您将两个参数传递给
data()
函数时,它会将第二个参数作为值附加到第一个参数,因此
yes
将影响到已播放的
数据
属性

注意:您应该在此处查看您的逻辑,我建议改为使用以下条件结构,以便您可以在单元格可用时检查这两种选择:

$('.cell').on('click', function () {
    if ( $(this).data('already-played')!=='yes' ) {
        if( currentTurn === 'X' ){
          $(this).text('X')
          $(this).data('already-played', 'yes')
          currentTurn = 'O'
        } else {
          $(this).text('O')
          $(this).data('already-played', 'yes')
          currentTurn = 'X'
        }
    }else{
        alert( 'This cell was already filled.' );
    }
});

看起来你的条件语句有点不对劲。考虑到玩家X的转弯,他点击已经播放过的单元格。然后文本设置为“O”,现在又轮到X了。这有意义吗?您可以重新构造条件语句,首先检查轮到谁了。然后,在该条件语句中,放入另一个检查该单元格是否已播放的语句。
$('.cell').on('click', function () {
    if ( $(this).data('already-played')!=='yes' ) {
        if( currentTurn === 'X' ){
          $(this).text('X')
          $(this).data('already-played', 'yes')
          currentTurn = 'O'
        } else {
          $(this).text('O')
          $(this).data('already-played', 'yes')
          currentTurn = 'X'
        }
    }else{
        alert( 'This cell was already filled.' );
    }
});