jQuery存储数据以供日后检查

时间:2018-08-08 17:38:05

标签: javascript jquery

.cell类是井字游戏桌的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'
}

数据属性是否适用于这种情况,或者有人指出如何对此进行调整?

1 个答案:

答案 0 :(得分:0)

您应该替换:

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

通过:

$(this).data('already-played')!=='yes'

由于当您将两个参数传递给data()函数时,它将把第二个参数作为值附加到第一个参数,因此yes将受到data-already-played属性的影响。 / p>

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

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