Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 选择特定div以使用eventListener设置属性_Javascript_Css - Fatal编程技术网

Javascript 选择特定div以使用eventListener设置属性

Javascript 选择特定div以使用eventListener设置属性,javascript,css,Javascript,Css,我已经完成了这个游戏,但我正在研究如何在胜利者的方块上涂上颜色或画一条线。制作方块或线条的css很简单,但当我的WinningCombo看起来像这样时,我不知道如何只选择获胜的方块: const winningCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] 以及玩家的移动方式被插入到一个数组中,以便稍后检查连击。例如,也许一个玩家需要5步才能赢,但我只需要赢3个方块 xChoi

我已经完成了这个游戏,但我正在研究如何在胜利者的方块上涂上颜色或画一条线。制作方块或线条的css很简单,但当我的WinningCombo看起来像这样时,我不知道如何只选择获胜的方块:

const winningCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]

以及玩家的移动方式被插入到一个数组中,以便稍后检查连击。例如,也许一个玩家需要5步才能赢,但我只需要赢3个方块

xChoices = [0,1,3,6] // where 0,3,6 are winners and I want to draw a line on them or put a colour
我检查组合的方式:

function checkForXWinner(){
        return winningCombos.some(combo =>{
            return combo.every(e =>{
                return xChoices.includes(e)
            })
        })
    }

    function checkForOWinner(){
        return winningCombos.some(combo =>{
            return combo.every(e =>{
                return oChoices.includes(e)
            })
        })
    }

这是JSFIDLE,干杯

试试看

 boxes = Array.from(document.querySelectorAll('.col'))
 const winCombo = () => {
   let wonCombo = []
   winningCombos.forEach(combo => {
     if (boxes[combo[0]].innerHTML == boxes[combo[1]].innerHTML && boxes[combo[0]].innerHTML == boxes[combo[2]].innerHTML && boxes[combo[0]].innerHTML != "")
       wonCombo = combo
   })
   return wonCombo
 }

这将返回获胜的组合。现在,您可以在wonCombo位置使用div,并在其上应用所需的css。

既然您要为这些方块上色,您还可以在多维数组中找到相应的数组,并分别为每个方块上色

例如:

const winningCombos = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]

xChoices = [0, 1, 3, 6]

const winArrayIndex = winningCombos
  .map(arr => arr.every(y => xChoices.includes(y)))
  .findIndex(x => x)

for (let i = 0; i < winningCombos[winArrayIndex].length; i++) {
  console.log('color:', winningCombos[winArrayIndex][i])
}
const winningCombos=[
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
xChoices=[0,1,3,6]
常量winArrayIndex=winningCombos
.map(arr=>arr.every(y=>xChoices.includes(y)))
.findIndex(x=>x)
for(设i=0;i
将组合的结果存储在变量中。检查它是否正确。如果为true,则组合包含要着色的字段。最后,返回变量。(另外,如果将
xChoices
/
oChoices
作为变量传递给函数,则不需要其中两个)