如何检查,单独和总共单击一次动态创建按钮的频率?

发布于 2025-01-29 20:41:56 字数 1099 浏览 3 评论 0原文

我创建了一个带有按钮的循环。我还创建了一个EventListener,可以为每个按钮保持计数。我希望在所有按钮都至少按至少3次按下时会发生一些事情,所以我创建了一个IF语句,检查计数是否为3,并将1添加到另一个计数中,但另一个计数仍在1上,即使按下了多个按钮3次。

for (let i = 0; i < 7; i++) {
  let btn = document.createElement('button');

  btn.classList.add('buttons');
  btn.id = 'button' + i;

  document.getElementById('box').appendChild(btn);

  let count = 0;
  let count2 = 0;

  btn.addEventListener('click', () => {
    count++;
    console.log(count);

    if (count === 3) {
      console.log('3');

      count2++;
      console.log(count2);
    } else {

      console.log('not 3');
    }
  });
}
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }
<div class="box" id="box">
</div>

因此,计数变量可以正常工作,当单击1个按钮3倍时,计数2变量更改为1,但它停留在1上,我似乎找不到原因。最后,Count2应该是7,因为有7个按钮。

I created a loop with buttons in it. I also created an eventListener that keeps a count for every button. I want something to happen when all buttons have been presses at least 3 times, so I created an if statement that checks if the count is 3 and adds 1 to another count, but the other count stays on 1 even if multiple buttons have been pressed 3 times.

for (let i = 0; i < 7; i++) {
  let btn = document.createElement('button');

  btn.classList.add('buttons');
  btn.id = 'button' + i;

  document.getElementById('box').appendChild(btn);

  let count = 0;
  let count2 = 0;

  btn.addEventListener('click', () => {
    count++;
    console.log(count);

    if (count === 3) {
      console.log('3');

      count2++;
      console.log(count2);
    } else {

      console.log('not 3');
    }
  });
}
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }
<div class="box" id="box">
</div>

So the count variable works fine, and when 1 button has been clicked 3 times the count2 variable changes to 1, but it stays on 1 and I can't seem to find out why. At the end count2 should be 7, because there are 7 buttons.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乖乖公主 2025-02-05 20:41:56

除了所有已经指出OP问题的评论外,我还建议基于存储/更新a map -instance。

引入 event-delegation 顶部将消除多个(对于每个动态创建的按钮) )应用的事件处理程序迫使处理不同的计数器示波器的方法(处理程序范围和块范围的)。

单个处理程序将完全订阅一次单个父母节点的'单击' -event。该处理程序通过查找单个点击计数来跟踪并处理各种点击计数状态。

function createButton(id) {
  let elmNode = document.createElement('button');

  elmNode.classList.add('buttons');
  elmNode.id = `button${ id }`;

  return elmNode;
}
function main() {

  // keeps track of and handles the various click count states.
  function handleButtonClick({ target }) {
    const btnNode = target.closest('button');

    // update a single buttons click count total.
    const buttonClickTotal = clickCountStorage.get(btnNode) + 1;
    clickCountStorage.set(btnNode, buttonClickTotal);

    const clickCountList =  Array
      .from(
        clickCountStorage.values()
      );
    // calculate click count total of all buttons.
    const allButtonsClickTotal = clickCountList
      .reduce((total, count) => total + count, 0);

    // check whether the OP's each button minimum 3 times click applies.
    const isEveryButtonHasBeenClickedAtLeastThreeTimes = clickCountList
      .every(count => count >= 3);

    console.log({
      buttonClickTotal,
      allButtonsClickTotal,
      isEveryButtonHasBeenClickedAtLeastThreeTimes,
    });
  }
  const clickCountStorage = new Map;

  const root = document.querySelector('#box');
  // make use of event delegation ...
  // - a single eventhandler subscribed once to
  //   a single parent node's 'click' event.
  root.addEventListener('click', handleButtonClick)

  for (let elmNode, i = 0; i < 7; i++) {
    elmNode = createButton(i);

    // establish a new button reference related click count.
    clickCountStorage.set(elmNode, 0);

    root.appendChild(elmNode);
  }
} 
main();
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }
<div class="box" id="box">
</div>

In addition to all the comments which already did point to the OP's problem I suggest a different approach based on storing/updating individual button-counts within a Map-instance.

With introducing event-delegation on top one would get rid of multiple on the fly (for each dynamically created button) applied event handlers which forces the approach to deal with different counter scopes (handler scope and the for block scope).

There will be exactly a single handler subscribed once to a single parent-node's 'click'-event. This handler keeps track of and handles the various click-count states by looking up a buttons individual click-count.

function createButton(id) {
  let elmNode = document.createElement('button');

  elmNode.classList.add('buttons');
  elmNode.id = `button${ id }`;

  return elmNode;
}
function main() {

  // keeps track of and handles the various click count states.
  function handleButtonClick({ target }) {
    const btnNode = target.closest('button');

    // update a single buttons click count total.
    const buttonClickTotal = clickCountStorage.get(btnNode) + 1;
    clickCountStorage.set(btnNode, buttonClickTotal);

    const clickCountList =  Array
      .from(
        clickCountStorage.values()
      );
    // calculate click count total of all buttons.
    const allButtonsClickTotal = clickCountList
      .reduce((total, count) => total + count, 0);

    // check whether the OP's each button minimum 3 times click applies.
    const isEveryButtonHasBeenClickedAtLeastThreeTimes = clickCountList
      .every(count => count >= 3);

    console.log({
      buttonClickTotal,
      allButtonsClickTotal,
      isEveryButtonHasBeenClickedAtLeastThreeTimes,
    });
  }
  const clickCountStorage = new Map;

  const root = document.querySelector('#box');
  // make use of event delegation ...
  // - a single eventhandler subscribed once to
  //   a single parent node's 'click' event.
  root.addEventListener('click', handleButtonClick)

  for (let elmNode, i = 0; i < 7; i++) {
    elmNode = createButton(i);

    // establish a new button reference related click count.
    clickCountStorage.set(elmNode, 0);

    root.appendChild(elmNode);
  }
} 
main();
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }
<div class="box" id="box">
</div>

你在看孤独的风景 2025-02-05 20:41:56

正如弗拉基米尔在评论中暗示的那样,这是一个范围的问题。

变量计数仅在事件侦听器中声明,因此,稍后,当您按不同的按钮时,您的代码确实count ++对于不同的计数变量。

要求解此声明var count而不是令count - 将其全局。

或在循环的之前声明计数变量。

顺便说一句:确保停止更新计数,因为它不会更新count2如果到4或更高

as Vladimir implied in the comments its a scoping problem.

The variable count is only declared inside the event listener, so later on when you press different button your code does count++ for a different count variable.

To solve this declare var count instead of let count - that will make it global.

Or declare the count variable before the for loop.

BTW: make sure to stop updating count as it gets to 3, since it wouldn't update count2 if it gets to 4 or above

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文