【问题标题】:jQuery won't recognize button clicks from $(".class").click() or $(".class").on() but works with $(".class").live()jQuery 无法识别来自 $(".class").click() 或 $(".class").on() 的按钮点击,但可以使用 $(".class").live()
【发布时间】:2019-06-05 20:23:59
【问题描述】:

使用已弃用的.live() 方法,我可以完全按照我的意愿完成这项工作,但是保持这种方式并不理想。我发现了类似的问题,建议使用$(".update").on() 方法或调用$(document).on('click', $('.update'), function()...),但是我无法使任何解决方案起作用。我能做的最好的事情就是返回完整的表,但永远无法获得我的 snap.key。除了.live() 之外的任何建议都将非常感谢。

  <table id="itemTable">
    <thead>
    <tr>
      <th>Item</th>
      <th>Cost</th>
      <th>Quantity</th>
      <th></th>
    </tr></thead>
    <tbody id = "tableBody">
    </tbody>
  </table>

Firebase 调用:

db.on('child_added', snap => {
    $('#tableBody').append('<tr><td class="up"><span>' + snap.key + '</span></td><td><button type = "button" class="update">Update</button></td></tr>');
});

按钮处理程序:

$(".update").live('click',function() {
  var $row = $(this).closest("tr");   // Find the row
  var $text = $row.find(".up").text(); // Find the text
  console.log($text);
});

【问题讨论】:

  • 我的猜测是 .update 元素直到 Firebase 调用完成后才存在,所以 clickon 只附加到页面上当前存在的项目,有没有什么可附加的。已弃用的 live 适合您,因为它附加到“现在和将来”的选择,而不仅仅是“现在”。您可以将clickon 附加到父元素,并指定它应该实际侦听的子选择。看到这个帖子:stackoverflow.com/questions/1359018/…

标签: jquery html firebase button html-table


【解决方案1】:

你想要:

$(document).on('click', '.update', function(){...});

请注意,on 的第二个参数是一个选择器,而您传递的是 $('.update')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多