【问题标题】:jQuery click not firing on asynchronously added elements [duplicate]jQuery单击未在异步添加的元素上触发[重复]
【发布时间】:2013-04-01 01:18:08
【问题描述】:

我看到了其他应该回答我的问题,但由于某种原因,他们没有。我指的是这些:
- jquery click event not firing?
- jquery functions dont work on dom elements loaded asynchromously

我首先使用 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>

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>

有人知道吗?
非常感谢!

【问题讨论】:

    标签: jquery asynchronous append


    【解决方案1】:

    你需要基于.on()使用事件delegation

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

    演示:Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多