Почему classList содержит возвращает false после вызова addChild для элемента div с помощью JavaScriptCSS

Разбираемся в CSS
Ответить Пред. темаСлед. тема
Anonymous
 Почему classList содержит возвращает false после вызова addChild для элемента div с помощью JavaScript

Сообщение Anonymous »

У меня есть проект шашек, который я пытаюсь отладить. Я использую эту логику для перемещения фигур. Я экспериментирую со свойствами CSS, чтобы удалить фрагменты из предыдущих блоков и добавить их в целевые блоки. Предположим, игрок нажимает на ячейку A, содержащую золотую монету, тогда я использую этот код, чтобы проверить, содержит ли ячейка золотую монету
if (event.target.classList.contains('gold-piece'));

Этот метод возвращает true до того, как эта фигура была перемещена, но возвращает false в новой ячейке, куда была перемещена золотая монета. Это логика, которую я использую для удаления свойства стиля CSS «золотая монета» из исходной ячейки и добавления его в новую ячейку, чтобы создать иллюзию хода шашки
if (lastcell != null) {
console.log("previous tapped cell is not null");
//get the cell that was previously tapped
//make sure the rows and the columns have a difference of 1
let x1 = lastcell[0]; let y1 = lastcell[1];
if (col < y1) {
//it is a move towards the left
if ((y1 - col) == 1 && (row - x1) == 1) {
//the move is valid
let original = getTableCell(table, x1, y1);
let child = original.querySelector("div.gold-piece");;
if (child != null) {
original.removeChild(child);
}
//move the piece to the target cell
let target = getTableCell(table, row, col);
const div = document.createElement("div");
div.classList.add("gold-piece");
target.appendChild(div);
B = true;
A = false;
} else {
console.log("the move is not valid");
A = true;
B = false;
//clear the dictionary after a move
lastTappedA = {}
}
} else {
//it is a move towards the right
if ((col - y1) == 1 && (row - x1) == 1) {
//the move is valid
let original = getTableCell(table, x1, y1);
let child = original.querySelector("div.gold-piece");;
if (child != null) {
original.removeChild(child);
}
//move the piece to the target cell
let target = getTableCell(table, row, col);
const div = document.createElement("div");
div.classList.add("gold-piece");
target.appendChild(div);
B = true;
A = false;
lastTappedA = {}
} else {
console.log("the move is not valid");
A = true;
B = false;
}
}

}

Я программно создаю дочерний элемент div, затем добавляю к нему стиль золотой монеты, а затем добавляю его в целевую ячейку, затем удаляю золотую монету из исходной ячейки с помощью RemoveChild но когда я нажимаю на новую ячейку, в которую была добавлена ​​золотая монета, строка event.target.classList.contains('gold-piece') возвращает false, несмотря на то, что в этой ячейке есть элемент золотой монеты.
Я ожидал, что новая ячейка, в которой находится золотая монета, с помощью метода element.appendChild() вернет true, вместо этого она возвращает false. Почему это и как я могу решить проблему?
Полный код приведен ниже: нажмите на желтую фигуру и сделайте ход, затем нажмите на красную фигуру и сделайте ход, затем вернитесь к исходной желтой фигуре, которую вы нажали, и обратите внимание, что она не выделен белым цветом, что означает, что строка event.target.classList.contains('gold-piece') возвращает false
HTML













CSS
body{
background:green;
}
/*style the table*/
.table{
margin:auto;
width:800px;
height:800px;
}
.square{
width:100px;
height:100px;
}
.white{
background-color:mintcream;
}
.brown{
background-color:chocolate;
}
/*styles for the pieces*/
.gold-piece {
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
background-color: gold;
width: 80%;
height: 80%;
border-radius: 50%;
margin: 10%;
}

.red-piece {
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
background-color:orangered;
width: 80%;
height: 80%;
border-radius: 50%;
margin: 10%;
}

/*style for styling a selected piece*/
.selected-piece{
border:2px solid white;
}

JS
goldpiece.addEventListener('click', function (event) {
if (A) {
if (event.target.classList.contains('gold-piece')) {
//means the cell contains a piece
console.log("gold piece tapped");
//highlight this piece and remove highlights from any previous square
const goldpieces = document.querySelectorAll('.gold-piece');
console.log(goldpieces.length);
goldpieces.forEach(function (element) {
if (element.classList.contains('selected-piece')) {
//remove the highlight from previous cells
element.classList.remove('selected-piece');
}
});
event.target.classList.add('selected-piece');
//check if the piece can make a jump over opponent pieces
let canJump = canJumpOverOpponent(table, row, col);
if (canJump) {
//this yellow piece can jump over opponent piece
console.log("yellow piece can jump over red piece");
//chek the direction of the capture
let x1 = row + 1; let y1 = col - 1; let x2 = row + 1; let y2 = col + 1;
let cellA = getTableCell(table, x1, y1);
let cellB = getTableCell(table, x2, y2);
let red = cellA.querySelector("div.red-piece");
let redr = cellB.querySelector("div.red-piece");
if (red != null && redr != null) {
//this yellow piece can capture in both directions
console.log("this piece can capture in both directions");
//update the variable that tells the player A to complete a capture
captureAStarted = true;
//write the cell to the dictionary
lastTappedA["lasttap"] = [row, col];
//exchange turns
A = false;
B = true;
} else if (red != null && redr == null) {
//this piece is capturing towards the left
console.log("this piece can capture towards the left");
captureAStarted = true;
lastTappedA["lasttap"] = [row, col];
A = false;
B = true;
} else if (red == null && redr != null) {
console.log("this piece can can capture towards the right");
captureAStarted = true;

lastTappedA["lasttap"] = [row, col];
A = false;
B = true;
} else {
//means this piece canno capture
console.log("this piece cannot capture, checking if it can move");
}
} else {
console.log("this piece cannot capture, checking if it can move");
if (canYellowPieceMove(table, row, col)) {
console.log("this yellow piece can move");
lastTappedA["lasttap"] = [row, col];
A = true; B = false;
captureAStarted = false;
} else {
console.log("this yellow piece cannot move");
}
}

} else {

console.log("piece does not contain a gold piece");
}
} else {
console.log("it is the turn of player two");
}
});

Я нашел это, ошибка в том, что я сказал своему коду выполнять функцию для золотой монеты всякий раз, когда строка меньше 3, я должен переместить блок за пределы блока if и моего кода должно работать
//this conditional structure is the problem because it will check
//and return false whenever a piece moves to row 3 or greater
if (row < 3) {
const goldpiece = document.createElement('div');
goldpiece.classList.add('gold-piece');
newCell.appendChild(goldpiece);
goldpiece.addEventListener('click', function (event) {
if (A) {


Подробнее здесь: https://stackoverflow.com/questions/785 ... iv-element
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Тестирование classlist.contains перед попыткой classlist.remove?
    Anonymous » » в форуме Html
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • Тестирование classlist.contains перед попыткой classlist.remove?
    Anonymous » » в форуме Javascript
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Тестирование classlist.contains перед попыткой classlist.remove?
    Anonymous » » в форуме Html
    0 Ответы
    7 Просмотры
    Последнее сообщение Anonymous
  • Тестирование classlist.contains перед попыткой classlist.remove?
    Anonymous » » в форуме Html
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • Тестирование classlist.contains перед попыткой classlist.remove?
    Anonymous » » в форуме Javascript
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous

Вернуться в «CSS»