在元素被销毁并再次初始化后再次分配事件

assign event again after element is destroyed and initialized again

让我用 bootstrap-select:

的例子来说明我的意思

HTML

<a href="#" id="link">Show Select options</a>
<div id="gap"></div>
<a href="#" id="link2">Destroy Select</a>

<div id="searchSelect">
  <select name="searchName" id="idSelect" data-live-search="true" data-size="10">
    <option value="John">John</option>
    <option value="Janet">Janet</option>
  </select>
</div>

JS:

$("#idSelect").selectpicker();

$("#link").click(function(e) {
  e.preventDefault();
  $("#searchSelect").show();
  setTimeout(function () {
     $('#idSelect').selectpicker('toggle');
  });
});

$("#link2").click(function(e) {
  e.preventDefault();
  $('#idSelect').selectpicker('destroy');
  $("#searchSelect").hide();
  alert("Select destroyed");
});

$("#idSelect").on("hide.bs.select", function () {
  alert("onHide fired");
});

当您第一次 运行 时,此事件正常运行:

$("#idSelect").on("hide.bs.select", function () {

但是在你销毁元素并再次初始化后,事件将不再触发,有没有办法将事件再次分配给元素?

理解我的意思的最好方法是通过: 看看 JSFIDDLE

  1. 单击按钮 "Show Select options"
  2. 在下拉菜单外单击,它将关闭并显示警告消息。
  3. 点击按钮"Destroy Select"
  4. 重复步骤 1,2 它将关闭,但不会显示警告消息。

更改为使用委托事件处理程序:

  $(document).on("hide.bs.select", "#idSelect", function () {
    alert("onHide fired");
  });

Jsfiddle:https://jsfiddle.net/n1zz8kkw/17/

它的工作原理是在不变的祖先上列出事件,然后将过滤器 (#idSelect) 应用于气泡链中的项目,然后将函数应用于引起事件的匹配元素.结果是元素不需要存在,除非在事件时间。

如果没有其他更接近的话,

document 是最好的默认值。 body 有一个错误,所以最好避免 document 总是 存在,因此文档上的委托处理程序甚至不需要在文档就绪处理程序中: )