JavaScript - 数组包含 HTMLDivElements 而不是元素(数字)中的 textContent

问题描述 投票:0回答:1

我正在开发一款普通的 JavaScript 宾果游戏。我创建宾果卡元素,然后创建一个网格。我创建了 5 个数组,每个数组有 5 个随机数。然后,对于每个数组中的每个数字,我创建一个 div 元素,向该元素添加“标记”类,将随机数字作为 textContent 粘贴,并将该元素附加到 HTML。创建卡片效果很好。我还设置了在卡片上标记空格。当一个空格被标记时,我会添加一个“标记”类。

现在我试图返回一个标记空格的数组(这是检查该人是否有实际宾果游戏的方法的第一部分)。我使用 querySelectorAll(".marker") 获取所有卡片空间。然后,我运行 Array.from 过滤器方法来提取包含“标记”类的空格。然后,我将该空间(div 元素)中的 textContent(数字)分配给一个变量并返回该变量。我有一个 console.log 在返回之前告诉我 textContent 是什么。过滤完成后,我会创建一个数组的 console.log,该数组应该包含所有元素的 textContents 中的值。

问题在于,最终的控制台日志不是显示空格中的数字,而是如下所示:

The marked spaces are: [object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement]

过滤器内的控制台日志显示了文本内容的实际数字,这就是我在过滤器方法中返回的内容。那么为什么我保存这些数字的数组将每个数字显示为 HTMLDivElement 而不是像内部控制台日志那样的字符串/数字?

这是我的 JavaScript 代码:

const bingoCard = () => {
    const bingoCardSpace = document.getElementById('bingo-card');
    const cardSheet = document.createElement("main");
    cardSheet.classList.add('inline-block', 'mx-auto', 'min-w-fit', 'border-8', 'bg-[#4bb2d3]', 'border-[#4bb2de]');
    bingoCardSpace.appendChild(cardSheet);

    const cardHeader = document.createElement('header');
    cardHeader.classList.add('flex', 'rounded-xl', 'bg-[#345995ff]');
    cardSheet.appendChild(cardHeader);

    const cardLetters = ['B', 'I', 'N', 'G', 'O'];

    for (let i = 0; i < cardLetters.length; i++) {
        const headerCell = document.createElement('div');
        headerCell.textContent = cardLetters[i];
        headerCell.classList.add('w-28', 'h-28', 'font-chewy', 'text-7xl', 'flex', 'justify-center', 'items-center', 'bg-[#f5f5f4ff]','rounded-full', 'mx-2', 'my-2');
        if (i != cardLetters.length - 1) headerCell.classList.add('mr-2');
        cardHeader.appendChild(headerCell);
    }

    const card = document.createElement("div");
    card.setAttribute("id", "card");
    card.classList.add('inline-grid', 'grid-rows-5', 'grid-flow-col', 'bg-[#4bb2de]');
    cardSheet.appendChild(card);

    let cardNumbers = [];
    cardNumbers = createCardArrays();
    for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 5; j++) {
            const cardCell = document.createElement("div");
            let cardCellNumber = cardNumbers[i][j];
            if (i === 2 && j === 2) {
                cardCell.textContent = "FREE";
            } else {
                cardCell.textContent = cardCellNumber;
            }
            cardCell.classList.add('marker', 'w-28', 'h-28', 'font-lato', 'text-5xl', 'flex', 'justify-center', 'items-center', 'bg-[#f5f5f4ff]', 'rounded-full', 'mx-2', 'my-2', cardCellNumber);
            card.appendChild(cardCell);
        }
    }
    listenForMarkingSpaces();
}

function createCardArrays() {
    const cardNumbers = new Array(5);
    let max, min;
    for (let i = 0; i < 5; i++) {
        cardNumbers[i] = [];
        max = 15 * (i + 1);
        min = max - 14;
        cardNumbers[i] = generateRandomNumbers(5, min, max);
    }
    return cardNumbers;
}

function generateRandomNumbers(count, min, max) {
    let uniqueNumbers = new Set();
    while (uniqueNumbers.size < count) {
        uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
    }
    const uniqueNumbersArray = [...uniqueNumbers];
    return uniqueNumbersArray;
}

const bingoBalls = () => {
    const ballArray = [];
    for (let i = 1; i <= 75; i++) {
        ballArray.push(i);
    }
    return ballArray;
}

let bingoBallsNotDrawn = bingoBalls();
let bingoBallsDrawn = [];

const drawBingoBall = () => {
    let ballDrawn = 0;
    while (bingoBallsNotDrawn.indexOf(ballDrawn) === -1) {
        ballDrawn = Math.floor(Math.random() * 75) + 1;
    }
    bingoBallsNotDrawn = bingoBallsNotDrawn.filter(ball => ball !== ballDrawn);
    console.log('bingoBallsNotDrawn now has ' + bingoBallsNotDrawn.length + ' balls in it');
    if (ballDrawn >= 61) ballDrawn = 'O-' + ballDrawn;
    else if (ballDrawn >= 46) ballDrawn = 'G-' + ballDrawn;
    else if (ballDrawn >= 31) ballDrawn = 'N-' + ballDrawn;
    else if (ballDrawn >= 16) ballDrawn = 'I-' + ballDrawn;
    else ballDrawn = 'B-' + ballDrawn;
    bingoBallsDrawn.push(ballDrawn);
    showBallDrawnOnScreen(ballDrawn);
    addBallToBallsDrawnList(ballDrawn);
    console.log('bingoBallsDrawn now has ' + bingoBallsDrawn);
    console.log('bingoBallsNotDrawn: ' + bingoBallsNotDrawn);
}

const showBallDrawnOnScreen = (ballDrawn) => {
    const currentBall = document.getElementById('currentBall');
    currentBall.textContent = "";
    const currentBallNumber = document.createTextNode(ballDrawn);
    currentBall.appendChild(currentBallNumber);
}

const addBallToBallsDrawnList = (ballDrawn) => {
    const ballList = document.getElementById("accordion-content");
    const listedBall = document.createElement("div");
    listedBall.textContent = ballDrawn;
    listedBall.classList.add('text-4xl', 'text-center', 'py-2', 'px-4', 'border-r-2', 'border-l-2', 'border-b-2', 'border-[#714BDE]', 'text-[#714BDE]');
    ballList.appendChild(listedBall);
}

const listenForMarkingSpaces = () => {
    const spaces = document.querySelectorAll(".marker");
    spaces.forEach((space) => {
        space.addEventListener("click", function (evt) {
            space.classList.toggle('bg-[#f5f5f4ff]');
            space.classList.toggle('bg-[#26c485ff]');
            space.classList.toggle('marked');
        });
    });
} 

const toggleAccordion = () => {
    document.getElementById('accordion-content').classList.toggle("hidden");
    document.getElementById('arrow-icon').classList.toggle("rotate-180");
}

const startNewGame = () => {
    const ballList = document.getElementById("accordion-content");
    ballList.innerHTML = '';
    const currentBall = document.getElementById('currentBall');
    currentBall.textContent = '';
    const spaces = document.querySelectorAll(".marker");
    spaces.forEach((space) => {
        space.classList.remove('bg-[#f5f5f4ff]');
        space.classList.remove('bg-[#26c485ff]');
        space.classList.remove('marked');
        space.classList.add('bg-[#f5f5f4ff]');
    });
}

const checkIfMarksAreCorrect = () => {
    const spaces = document.querySelectorAll(".marker");
    const markedSpaces = Array.from(spaces).filter((space) => {
        if (space.classList.contains('marked')) {
            console.log(space.textContent);
            spaceNumber = space.textContent;
            return spaceNumber;
        }
    });
    console.log('The marked spaces are: ' + markedSpaces);
}

这是我的 HTML:

<div class="flex">
    <div class="w-3/4 h-100lvh flex flex-col border-r border-black-500" id="bingo-card">
        <div class="flex justify-center">
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="startNewGame()">New game</button>
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="bingoCard()">Click to create card</button>
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="drawBingoBall()">Click to draw ball</button>
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="checkIfMarksAreCorrect()">Click to check card</button>
        </div>
    </div>
    <div class="w-1/5">
        <div class="flex mt-4 text-[#714BDE] font-bold justify-center text-4xl">
            Current ball: <span id="currentBall" class="ml-4 text-[#A14BDE]"></span>
        </div>
        <div class="overflow-hidden" onclick="toggleAccordion()">
            <div class="flex text-4xl justify-center mx-4 mt-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE]">
                Balls drawn
                <span class="transform transition-transform" id="arrow-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                        stroke="currentColor" class="size-12">
                        <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
                    </svg>
                </span>
            </div>
            <div class="px-4 hidden" id="accordion-content">

            </div>
        </div>
    </div>
</div>
javascript arrays dom
1个回答
0
投票

问题发生在函数“checkIfMarksAreCorrect”中。当您使用过滤器方法时,您可以管理与条件匹配时将返回哪些数据。在这种情况下,如果元素已在类列表中“标记”。它不会操纵数据的返回方式。为此,您需要使用map()。尝试使用此代码:

const checkIfMarksAreCorrect = () => {
    const spaces = document.querySelectorAll(".marker");
    const markedSpaces = Array.from(spaces)
        .filter((space) => space.classList.contains('marked'))
        .map((markedSpace) => markedSpace.textContent.trim());

        console.log('The marked spaces are: ' + markedSpaces);
};
© www.soinside.com 2019 - 2024. All rights reserved.