【问题标题】:Input loses event after include a tr包含 tr 后输入丢失事件
【发布时间】:2013-04-29 16:43:52
【问题描述】:

我正在使用.on() 方法将以下事件绑定到输入:

$('table.transactions tbody input').on({
    "focus": function (e) { $(this).closest('tr').addClass('active'); },
    "blur": function (e) { $(this).closest('tr').removeClass('active'); }
});

当我在表格中包含一个新的 tr 时,新的输入会失去焦点和模糊事件:

$('.btn').on('click', function (e) {
    var $tr = $(this).closest('tr');
    $tr.after('<tr><td><input type="text" /><a href="" class="btn">Add Tr</a></td></tr>');
    e.preventDefault();
    return false;
});

当我使用.on() 方法时,新输入的焦点和模糊事件不应该是自动的吗?如果没有,如何再次绑定事件?

【问题讨论】:

  • 关键字是“事件委托”(我知道有两个),请参阅@Steven Vondruska 的回答

标签: jquery events dom bind


【解决方案1】:

尝试在稳定元素上使用委托来获取新添加的元素

$(document).on('click', '.btn', function(e) {
    // event data here
}

您可以将document 更改为包含元素,可能是包含您要添加的&lt;tr&gt; 的表。

参考:http://api.jquery.com/on/

【讨论】:

  • “.btn”的点击事件工作正常,问题在于输入模糊和焦点事件
  • 我使用:$('table.transactions tbody').on('focus', 'input', function (e) {
猜你喜欢
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多