在bootstrap3的模态中回调函数

我有点混淆在javascript模式的bootstrap3中触发回调函数。 在普通的jquery.post你可以这样做,

 $.post('path', { something: something }, function(data) { console.log(data); }); 

但是在bootstrap 3模式中我通过脚本激发模态,我这样做是基于我如何理解他们网站中的解释。

 $('selector').modal('show', function() { //here comes the problem, I have a button in the modal in the html, my code //if the button was clicked inside this modal is.. $('#myButton').on('click', function() { console.log("this is a try"); }); }); 

但遗憾的是,如果我点击按钮,没有任何事情发生,控制台中没有记录任何内容。 如何在一个bootstrap 3模式中调用回调函数?

对于Bootstrap 3,事件现在是命名空间,因此模态的show事件将是show.bs.modal

 $('#myModal').on('show.bs.modal', function (e) { alert('modal show'); }); 

演示: http : //bootply.com/90952

@Skelly是对的,您可以像这样使用show.bs.modal事件:

 $('#myModal').on('show.bs.modal', function (e) { alert('modal show'); }); 

官方文件说:

调用show实例方法时会立即触发此事件。

请注意,此事件“很快”被触发,您可能需要使用shown.bs.modal

有关此活动的文档:

当模态对用户可见时将触发此事件(将等待CSS过渡完成)。

这会影响@Keith yeoh的答案,你应该尽可能避免超时

来源: 官方Bootstrap文档

稍微为第一个答案添加一点,这是因为当回调被触发时,模态中的DOM还没有完全加载,也许应该做一点hack来阻止回调一段时间后的动作。 希望能帮助到你!

 $('#myModal').on('show.bs.modal', function (e) { setTimeout(function(){ // something here }, 300); }); 

我认为更好的是,使用“shown.bs.modal”它会在模态已经加载时被激活。 Bootstrap模态事件

 $('#myModal').on('shown.bs.modal', function (e) { alert('modal is allready shown'); }); 

用它包裹

 $(window).on('load', function() { ...modal callback here. });