jQuery单击不触发异步添加的元素

Kho*_*khe 2 jquery asynchronous append

我已经看到了应该回答我的其他问题,但由于某种原因,他们没有.我指的是:
- jquery点击事件没有解雇?
- jquery函数不适用于异步加载的dom元素

我首先使用click()尝试将所选"li"的颜色更改为粉红色.它有效,但不适用于动态附加的"li".我尝试使用on(),因为live()现已弃用.我很惊讶它仍然没有用.

这是您可以运行的示例:

使用Javascript:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("ol").append("<li class='test'> Appended item </li>");
  });
});
</script>

<script>
$(function () {
  $('.test').on('click', function () {
    $(this).css("background-color","pink");
  });
});
</script>
Run Code Online (Sandbox Code Playgroud)

HTML:

<body>
  <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>
  <ol>
    <li class='test'> List item 1 </li>
    <li class='test'> List item 2 </li>
    <li class='test'> List item 3 </li>
  </ol>

  <button id="btn1">Append list item</button>
</body>
Run Code Online (Sandbox Code Playgroud)

有人有线索吗?
非常感谢!

Aru*_*hny 12

您需要使用基于.on()的事件委派

$('ol').on('click', '.test', function(el){
    $(this).css("background-color","pink");
})
Run Code Online (Sandbox Code Playgroud)

演示:小提琴