无法让jQuerys .on使用动态元素,即使它已被委派

我有一个静态元素,但即使我使用它,.on也不会绑定到动态选择器。

这是一个比我正在工作的版本更简单的版本,但确实有相同的问题。

当我单击静态元素时,将创建div,但是单击动态元素不会执行任何操作。

希望这里有人能帮我。

HTML

?

$(document).ready(function() {

  var test = $('#test');

  test.click(function() {

    var html = document.createElement('div');
    html.className = 'temp';
    $('body').append(html);
    console.log('clicked.');

  });

  test.on('click', '.temp', function() {

    console.log('Temp div removed.');
    $(this).remove();

  });

});
#test {
  width: 300px;
  height: 75px;
  background: #f00;
  margin-bottom: 5px;
}

.temp {
  width: 200px;
  height: 50px;
  background: #00f;
  margin-bottom: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="test"></div>

?

转载请注明出处:http://www.jixiangdc.com/article/20230526/1056776.html