Bootstrap 3 - Event hidden.bs.collapse not fired if the accordion is inside a modal populated via ajax

ⅰ亾dé卋堺 提交于 2019-12-05 11:23:26

You are trying to attach your event listener to elements with the .panel class before any elements with the .panel class exist in the DOM.

To make your code work, you can move your $('.panel').on(...) inside the AJAX success callback, after the .panels have actually been inserted to the DOM. Alternatively, and probably preferably, you may use event delegation instead:

$('#modalbody').on('hidden.bs.collapse', '.panel', function (e) {
    alert('Event fired on #' + e.currentTarget.id);
});

See the discussion regarding event delegation in the jQuery documentation.

A relevant excerpt:

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated events to attach event handlers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!