简体   繁体   English

如何识别和比较在网格 JS 上单击了哪个单元格?

[英]How do I identify and compare which cell was clicked on a grid JS?

sorry that the post is a bit long its just to be very clear about what im need.抱歉,这篇文章有点长,只是为了非常清楚我需要什么。 I'm making a Board 8x8.我正在制作一个 8x8 板。 i did it like using loop.我喜欢使用循环。 works perfect.完美运行。

// Create a center tag to center all the elements
        var center = document.createElement('center');
        var count = 1;
        // Create a table element
        var ChessTable = document.createElement('table');
        for (var i = 0; i < 8; i++) {

            // Create a row
            var tr = document.createElement('tr');
            for (var j = 0; j < 8; j++) {

                // Create a cell
                var td = document.createElement('td');

                // If the sum of cell coordinates is even
                // then color the cell white
                if ((i + j) % 2 == 0) {

                    // Create a class attribute for all white cells
                    td.setAttribute('class', 'cell whitecell');
                    tr.appendChild(td);
                   // td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
                }

                // If the sum of cell coordinates is odd then
                // color the cell black
                else {

                    // Create a class attribute for all black cells
                    td.setAttribute('class', 'cell blackcell');

                    // Append the cell to its row
                    tr.appendChild(td);
                   // td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
                    
                }
            }

            // Append the row
            ChessTable.appendChild(tr);
        }
        center.appendChild(ChessTable);

        // Modifying table attribute properties
        ChessTable.setAttribute('cellspacing', '0');
        ChessTable.setAttribute('width', '270px');
        document.body.appendChild(center);
        console.log(ChessTable);

now i needed to make option that if you click on certain cell the cell changing color.现在我需要选择如果您单击某个单元格,则单元格会改变颜色。 works perfect too.也很完美。

 function respondToClick(event)
    {
        if (event.target.nodeName.toLowerCase() === 'td') {
            event.target.style.backgroundColor = "green";
        }
    }        ChessTable.addEventListener("click", respondToClick);

know i needed to random cells and then collor then.知道我需要随机单元格然后着色。 i did it to and works great, i did it using random function from 0-63, then convert the numbers to base 8, because i wanted to compare each cell to the row and column, then split the numbers to know each row and column.我做到了并且效果很好,我使用0-63的随机function做到了,然后将数字转换为以8为底,因为我想将每个单元格与行和列进行比较,然后拆分数字以了解每一行和每一列.

function getRandomArbitrary(min, max)
        {
            return Math.round(Math.random() * (max - min) + min);
        }
    //random numbers
    var a = [];
    for (var j = 0; j < 5; j++) {
        a[j] = getRandomArbitrary(0, 64)           
    }
    console.log(a)      
    var b = [];
    b = a;
    //convert to base 8
    for (var j = 0; j < 5; j++) {
       b[j]=b[j].toString(8);
    }

    console.log(b);
    const cells = []

    //seperate the digidt for board

    for (var j = 0; j < 5; j++)
    {
        b[j] = b[j].toString(8);
        var digits = b[j].toString().split('');
        var realDigits = digits.map(Number)
        console.log(realDigits);

        // coloring the random numbers
        if (realDigits[1] != null) {
             cells[j] = ChessTable.rows[realDigits[0]].cells[realDigits[1]];
            cells[j].style.backgroundColor = "yellow";
        }
        else {
            cells[j] = ChessTable.rows[0].cells[realDigits[0]];
            cells[j].style.backgroundColor = "yellow";
        }
    }

that`s work great too.那也很好用。

Now the last problem that i have is that i need to do this.现在我遇到的最后一个问题是我需要这样做。 first the computer need to random the cells, but don`t need to show them yet, when there is click in the mouse then the user need to know if the click was on cell that the computer chose randomly.首先计算机需要随机单元格,但不需要显示它们,当鼠标点击时,用户需要知道点击是否在计算机随机选择的单元格上。

so i added did this to the respondToClick function.所以我添加了这个到respondToClick function。

 function respondToClick(event, cells)
        {
            if (event.target.nodeName.toLowerCase() === 'td')
            {
                event.target.style.backgroundColor = "green";
                if (event.target.nodeName.toLowerCase() == cells[0]) {
                    alert("correct")
                }
            }
         }

in cells i have the "place of the cells(i added a photo) (cells[0] is just for testing, i can use loop there for each click to go over all the cells)在单元格中,我有“单元格的位置(我添加了一张照片)(单元格 [0] 仅用于测试,我可以在每次点击 go 的所有单元格时使用循环)

so when i compare the event to the cells[0], i`m getting error.所以当我将事件与单元格 [0] 进行比较时,我得到了错误。 what im missing here?我在这里缺少什么? 错误

You need to use bind or a closure to pass the cells parameter to the handler.您需要使用bind或闭包将单元格参数传递给处理程序。

const chessTableClickHandler = respondToClick.bind(null, cells);

ChessTable.addEventListener("click", chessTableClickHandler);

function respondToClick(cells, event)
        {
            if (event.target.nodeName.toLowerCase() === 'td')
            {
                event.target.style.backgroundColor = "green";
                if (event.target.nodeName.toLowerCase() == cells[0]) {
                    alert("correct")
                }
            }
         }

First, let's organize your code better, so it is easier to work with the board.首先,让我们更好地组织您的代码,以便更轻松地使用该板。

You are currently making the board using a table, which I don't recommend.您目前正在使用桌子制作电路板,我不建议这样做。 Instead, it would be better to use a <div> .相反,最好使用<div>

Also, you are using a two-dimensional array, that isn't needed, and can sometimes overcomplicate the code.此外,您使用的是不需要的二维数组,有时会使代码过于复杂。

I would recommend using a one dimensional array instead.我建议改用一维数组。

function makeBoard(height, width, init_callback){
    return Array(height*width).fill(0).map(init_callback);
}

Make board will create an array of the length height * width, and populate it using the callback function. Make board 将创建一个长度为高度 * 宽度的数组,并使用回调 function 填充它。

The callback would look something like this:回调看起来像这样:

function initCell(){
    const cell = document.createElement("div");
    // make changes to cell
    cell.classList.add("cell")
    return cell
}

You can then add the grid to your HTML easily, by using .append() .然后,您可以使用.append()轻松地将网格添加到 HTML 中。

//  <div id="board" />
const board = document.querySelector("#board");

const pieces = makeBoard(8, 9, initCell);

// append can take multiple elements. Making it easy to add our elements by de-structering our array.
board.append(...pieces); 

Now, to style the board, we don't need to use JavaScript.现在,要设计电路板样式,我们不需要使用 JavaScript。 CSS is very powerful and can easily handle it for us. CSS 功能非常强大,可以轻松为我们处理。

.cell {
  height: 40px;
  width: 40px;
  background-color: white;
}

.cell:nth-child(odd){
  background-color: brown;
}

.cell:nth-child(9n+1){
  display: none;
}

#board {
  height:  320px;
  width: 320px;
  display: grid;
  grid-template-columns: repeat(8, 40px);
}

If you look at the precious JS and CSS, our grid is actually 8x9 and not 8x8.如果你看珍贵的JS和CSS,我们的网格实际上是8x9而不是8x8。 This is because, to easily create a chessboard pattern, we are creating a 8x9 board and then removing the 9th cell of each row, to create the chessboard.这是因为,为了轻松创建棋盘图案,我们创建了一个 8x9 棋盘,然后删除每行的第 9 个单元格,以创建棋盘。

Now to add the click events, it's relatively easy.现在添加点击事件,相对容易。

document.querySelectorAll(".cell").forEach(cell => {
    cell.addEventListener("click", cellClickHandler)
});

That code will set the onClick event on the cells to the cellClickHandler function.该代码会将单元格上的onClick事件设置为cellClickHandler function。

To change the bg-color, when clicked, it would look like this:要更改背景颜色,单击时会如下所示:

function cellClickHandler(e){
    e.target.classList.toggle("green")
}

Now here's a runnable version, to see what we have so far:现在这是一个可运行的版本,看看我们到目前为止有什么:

 function makeBoard(height, width, init_callback){ return Array(height*width).fill(0).map(init_callback) } function initCell(){ const cell = document.createElement("div"); // make changes to cell cell.classList.add("cell"); return cell } // <div id="board" /> const board = document.querySelector("#board"); const pieces = makeBoard(8, 9, initCell); board.append(...pieces); document.querySelectorAll(".cell").forEach(cell => { cell.addEventListener("click", cellClickHandler) }); function cellClickHandler(e){ e.target.classList.toggle("green") }
 .cell { height: 40px; width: 40px; background-color: white; }.cell:nth-child(odd){ background-color: brown; }.cell:nth-child(9n+1){ display: none; border: none; }.green { background-color: green;important: } #board { height; 320px: width; 320px: display; grid: grid-template-columns, repeat(8; 40px); }
 <div id="board" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM