我正在尝试将变量的值分配给"数据索引"属性



我正在为Tic-Tac-Toe项目开发"计算机移动"选项。我的游戏板网格由具有相同类(.box(的按钮组成。我使用Jquery在单击"计算机移动"按钮时触发网格元素的onClick功能。

$('.box[data-index="1"]').trigger('click', onUpdate)

这里的代码是有效的,但我想使用一个随机生成的数字,我已经存储在一个变量中。如下所示:

$('.box[data-index=compChoice]').trigger('click', onUpdate)

然而,这是行不通的。我试过带引号和不带引号。

我还尝试过以各种不同的方式和不同的语法使用一些不同的Jquery方法,如.attr((、.val((、.get((,但运气不太好。

任何帮助都将不胜感激。

这是我的游戏板:

<div class="row">
<button data-index="0" class="col-2 box alt-color"></button>
<button data-index="1" class="col-2 box alt-color"></button>
<button data-index="2" class="col-2 box alt-color"></button>
</div>
<div class="row">
<button data-index="3" class="col-2 box alt-color"></button>
<button data-index="4" class="col-2 box alt-color"></button>
<button data-index="5" class="col-2 box alt-color"></button>
</div>
<div class="row">
<button data-index="6" class="col-2 box alt-color"></button>
<button data-index="7" class="col-2 box alt-color"></button>
<button data-index="8" class="col-2 box alt-color"></button>
</div>

这是我的电脑移动功能:

const onCompMove = function (event) {
event.preventDefault()
const compChoices = store.game.cells
const choices = []
for (let i = 0; i < compChoices.length; i++) {
if (compChoices[i] === '') {
choices.push(i)
}
}
const compChoice = choices[Math.floor(Math.random() * choices.length)]
store.compChoice = compChoice
console.log(compChoice)
$('.box[data-index=compChoice]').trigger('click', onUpdate)
}
const onUpdate = function (event) {
event.preventDefault()
console.log(event.target)
if (store.game.over === false) {
if ($(event.target).text() !== '') {
return ui.invalidMove()
} else if ($(event.target).text() === '') {
$(event.target).text(store.turn)
}
const index = $(event.target).attr('data-index')
const value = store.turn
takenIndex.push(index)
// console.log(takenIndex)
api.update(index, value)
.then(ui.onUpdateSuccess)
.catch(ui.onUpdateFailure)
} else {
ui.invalidGameOver()
}
switchPlayer()
}

变量没有在字符串中展开,您需要连接:

$('.box[data-index=' + compChoice + ']').trigger('click', onUpdate)

或者使用ES6模板文字

$(`.box[data-index=${compChoice}]`).trigger('click', onUpdate)

最新更新