jQuery DOM 元素上的事件无法正常工作

jQuery event on DOM elements working not properly

正在研究一个简单的计算器和一个日志。每次计算得到结果后, 具有此结果的新记录出现在日志中。单击此日志项中的圆圈,圆圈应变为红色,i.e.toggled。但事件只有依次成功 - 第一个圆圈变红,第二个没有,第三个圆圈等等。尝试了一切,不知道发生了什么。请帮忙that's how it looks

    const mainOperationsBlock = $('.main');
    const numbersInput = $('#number-input');
    const log = $('#log');

    mainOperationsBlock.on('click', function() {
      if (numbersInput.text() === '0' && $(this).text() === '0') {
        numbersInput.text($(this).text());
      } else if (numbersInput.text().match(/[-\+\*\/]$/) && 
      $(this).text().match(/[-\+\*\/]/)) {
        numbersInput.text(numbersInput.text().substring(0, 
        numbersInput.text().length - 1) + ''+ $(this).text());
      } else if (/^0$/.test(numbersInput.text()) && 
      /[123456789]/.test($(this).text())) {
         numbersInput.text(numbersInput.text().substring(1, 
         numbersInput.text().length) + $(this).text());
      } else {
          numbersInput.text(numbersInput.text() + $(this).text());
      }
   });

    $('#erase').on('click', function() {
      numbersInput.text('0');
      numbersInput.removeClass('error');
    });

    $('#result').on('click', getResult);

    function getResult() {
      let result = eval(numbersInput.text());
      if(/[/]0/.test(numbersInput.text())) {
        numbersInput.text('ERROR');
        numbersInput.toggleClass('error');
      } else {
        $('#log').prepend(`
          <div class='log-item'>
            <span class='circle'></span>
            <p class='equation'>${numbersInput.text()}=${result} 
            </p>
            <span class='close'>&#10005;</span>
          </div>
`       );

    numbersInput.text(result);

    let logItems = $('.equation');
    logItems.each(function() {
        if(/(48)/.test($(this).text())) {
            $(this).css('text-decoration', 'underline');
        }
    });

    $('.circle').on('click', function() {
        $(this).toggleClass('red');
    });

    $('.close').on('click', function() {
      $(this).parent().remove();
    });
    }
   }

   log.scroll(function() {
     console.log(`Scroll Top: ${log.scrollTop()}`)
   });        

.circle.close 的事件处理程序在 getResult() 函数中...

所以每次函数 运行s,都会设置一个新的事件处理程序。这使得 .toggleClass 执行了很多次。如果函数 运行s 两次,则有两个事件处理程序...使切换 运行 两次...所以看起来根本没有 运行ning。

解决方案是将那些事件处理程序移出 getResult() 函数。

现在...这些元素是动态创建的...您必须使用delegation

因此您的处理程序将是:

$(document).on('click', '.circle', function() {
  $(this).toggleClass('red');
});

$(document).on('click', '.close', function() {
  $(this).parent().remove();
});