努力为div元素生成唯一ID

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

[我有一个名为generateUniqueCard(isEasy)的函数,该函数返回带有div个img元素的COUNT元素(如果为true,则isEasy参数返回纯色卡片)。基于#board中现有的卡,我试图确保从函数返回的所有divCard均具有STYLE-SHAPE-COLOR-COUNT形式的唯一ID。

我当前不适合我的当前方法是尝试在#board中创建div元素上使用querySelectorAll,然后运行带有条件的while循环以生成randomAttributes(generateRandomAttributes(isEasy)以创建唯一ID如果querySelector的ID为null(因为它为null,则该ID现在在开发板上尚不存在,以确保下一个生成的ID将是唯一的)。

现在,我遇到的问题是,在创建的div元素中所有生成的id是“ [object NodeList]”,而不是从generateRandomAttributes(isEasy)生成的randomAttributes>

代码段

  let timerId;
  let remainingSeconds;

  let totalCards;
  let easyDifficulty;

  const STYLE = ["solid", "outline", "striped"];
  const SHAPE = ["diamond", "oval", "squiggle"];
  const COLOR = ["green", "purple", "red"];
  const COUNT = [1, 2, 3];

  /**
   * Add a function that will be called when the window is loaded.
   */
  window.addEventListener("load", init);

  /**
   * CHANGE: Describe what your init function does here.
   */
  function init() {
    let startButton = document.getElementById("start-btn");
    let backButton = document.getElementById("back-btn");
    startButton.addEventListener("click", startGame);
    backButton.addEventListener("click", exitGame);
  }

  function startGame() {
    toggleViews();

    if (qs("input[type = \"radio\"]:checked").value === "easy") {
      easyDifficulty = true;
      totalCards = 9;
    } else {
      easyDifficulty = false
      totalCards = 12;
    }

    generateSetDeck(easyDifficulty, totalCards);
  }

  function generateSetDeck(easyDifficulty, totalCards) {
    for (let i = 0; i < totalCards; i++) {
      id("board").appendChild(generateUniqueCard(easyDifficulty));
    }
  }

  function toggleViews() {
    id("game-view").classList.toggle("hidden");
    id("menu-view").classList.toggle("hidden");
  }

  function exitGame() {
    clearInterval(timerId);
    toggleViews();
  }

  function generateRandomAttributes(isEasy) {
    let randStyle;
    if (isEasy === true) {
      randStyle = STYLE[0];
    } else {
      randStyle = STYLE[Math.floor(Math.random() * STYLE.length)];
    }
    var randShape = SHAPE[Math.floor(Math.random() * SHAPE.length)];
    var randColor = COLOR[Math.floor(Math.random() * COLOR.length)];
    var randCount = COUNT[Math.floor(Math.random() * COUNT.length)];
    var randAttributes = [randStyle, randShape, randColor, randCount];
    return randAttributes;
  }

  function generateUniqueCard(isEasy) {
    let divCards = gen('div');

    let randAttributesArray = generateRandomAttributes(isEasy);

    for (let i = 0; i < randAttributesArray[3]; i++) {
      let imgCards = gen('img');
      divCards.appendChild(imgCards);
      let imgFilePath = randAttributesArray[0] + "-" + randAttributesArray[1] + "-" +
        randAttributesArray[2];
      imgCards.src = "img/" + imgFilePath + ".png";
      imgCards.alt = randAttributesArray.join("-");
    }

    //let cardID = randAttributesArray.join("-");
    let boardChildren = qsa("#board div");

    while (id(boardChildren) == null && boardChildren.length > 0) {
      boardChildren = generateRandomAttributes(isEasy);
    }

    divCards.id = boardChildren;
    divCards.classList.add("card");
    divCards.addEventListener("click", cardSelected);

    return divCards;
  }
  
  function cardSelected() {
    console.log("selected");
    qsa(".card").classList.toggle(".selected")
  }
  
   /**
   * Returns the element that has the ID attribute with the specified value.
   * @param {string} idName - element ID
   * @returns {object} DOM object associated with id.
   */
  function id(idName) {
    return document.getElementById(idName);
  }

  /**
   * Returns the first element that matches the given CSS selector.
   * @param {string} selector - CSS query selector.
   * @returns {object} The first DOM object matching the query.
   */
  function qs(selector) {
    return document.querySelector(selector);
  }

  /**
   * Returns the array of elements that match the given CSS selector.
   * @param {string} selector - CSS query selector
   * @returns {object[]} array of DOM objects matching the query.
   */
  function qsa(selector) {
    return document.querySelectorAll(selector);
  }

  /**
   * Returns a new element with the given tag name.
   * @param {string} tagName - HTML tag name for new DOM element.
   * @returns {object} New DOM object for given HTML tag.
   */
  function gen(tagName) {
    return document.createElement(tagName);
  }
body, button, select, input {
  font-family: "Helvetica", "Verdana", sans-serif;
  text-align: center;
  font-size: 12pt;
}

main {
  width: 80%;
  margin: auto;
}

button, select {
  padding: 8px;
  background-color: white;
  border: 2pt solid black;
}

h2 {
  text-decoration: underline;
}

#start-btn {
  width: 100px;
  margin-top: 10px;
  margin-bottom: 20px;
}

#menu-view > article {
  background-color: #6F77ED;
  border-radius: 0.35em;
  border: 5pt solid black;
}

#menu-view > article, #details-bar {
  color: white;
}

.card, #details-bar, #board {
  display: flex;
  justify-content: space-evenly;
}

.card, #details-bar {
  align-items: center;
}

#details-bar {
  border-top-left-radius: 0.5em;
  border-top-right-radius: 0.5em;
  background-color: black;
  font-size: 14pt;
}

.card {
  width: 220px;
  height: 95px;
  border: 0.35em solid black;
  border-radius: 1em;
  cursor: pointer;
  margin-top: 5px;
  margin-bottom: 5px;
}

.card img {
  height: 85%;
}

.card p {
  font-weight: bold;
}

h2, .card p {
  font-size: 16pt;
}

.selected {
  box-shadow: #636363 6px 6px;
}

#board {
  border-right: black solid 5pt;
  border-left: black solid 5pt;
  border-bottom: black solid 5pt;
  padding: 20px;
  flex-wrap: wrap;
}

.hidden, .hide-imgs > img {
  display: none;
}
<html lang="en">

  <head>
    <meta charset="utf-8">
    <title>Set!</title>
    <link rel="stylesheet" href="set.css">
    <script src="set.js"></script>
  </head>

  <body>
    <header>
      <h1>Set!</h1>
    </header>

    <main>
      <section id="menu-view">
        <article>
          <h2>Choose a Timing Option:</h2>
          <select>
            <option value="60">1 Minute</option>
            <option value="180" selected>3 Minutes</option>
            <option value="300">5 Minutes</option>
          </select>

          <h2>Choose a Difficulty:</h2>
          <p>
            <label><input type="radio" name="diff" value="easy" checked> Easy</label>
            <label><input type="radio" name="diff" value="standard"> Standard</label>
          </p>

          <button id="start-btn">Start</button>
        </article>

        <section>
          <header>
            <h2>Rules</h2>
          </header>
          <p>
            Originally created by Marsha Jean Falco of Set Enterprises, Inc.,
            Set is a card game with a board of non-duplicate cards. There are two levels
            of difficulty for this game.
            In Standard
            Difficulty there are 4 different attributes (style, color, shape, and count) -
            each attribute can have one of three values. For example, shape can have 3
            values: "diamond", "oval", or "squiggle". In Easy Difficulty, all cards share a
            "solid" style attribute, so only the other 3 attributes can be different.
          </p>
          <p>
            A Set is a selection of 3 cards such that for each of attributes, all
            three cards have the same value or none of the cards have the same value.
            Your goal is to find as many Sets as you can on the board!
          </p>
          <p>Have fun!</p>
        </section>
      </section>

      <section id="game-view" class="hidden">
        <div id="details-bar">
          <button id="back-btn">Back to Main</button>
          <p><strong>Sets Found: </strong><span id="set-count">0</span></p>
          <p><strong>Time: </strong><span id="time">00:00</span></p>
          <button id="refresh-btn">Refresh Board</button>
        </div>
        <div id="board"></div>
      </section>
    </main>
  </body>

</html>

我有一个称为generateUniqueCard(isEasy)的函数,该函数返回具有COUNT个img元素的div元素(如果为true,则isEasy参数将返回卡片的实体样式)。基于现有卡...

javascript html dom nodelist
1个回答
0
投票
let boardChildren = qsa("#board div");

while (id(boardChildren) == null && boardChildren.length > 0) {
  boardChildren = generateRandomAttributes(isEasy);
}

divCards.id = boardChildren;
divCards.classList.add("card");
divCards.addEventListener("click", cardSelected);
© www.soinside.com 2019 - 2024. All rights reserved.