将事件处理程序附加到twitter bootstrap popover中的按钮

我正在使用twitter bootstrap popovers,

在popover我添加一个按钮,

我需要在按钮上附加一个click处理程序,但popover的工作方式是每次显示它删除并重新创建元素,而不是仅显示/隐藏它,因此删除我与所述按钮关联的任何事件处理程序。

我正在使用他们自己的按钮版本创建几个弹出窗口,所以只是将一个类应用于弹出窗口将不起作用(除非我为每个生成一个不同的类:/),该按钮可能有也可能没有它自己的ID ,所以不能申请身份证。

如何将事件处理程序应用于twitter bootstrap popover内容中的某些内容?

我遇到了同样的问题,在我的情况下, $(body).on('click')解决方法不起作用,因为应用程序有lotta单击按钮。

我改为做了以下。 这样,我们可以将delegate事件的范围限制为popover元素的父级。

 $('a.foo').popover({ html: true, title: 'Hello', placement: 'bottom', content: '' }).parent().delegate('button#close-me', 'click', function() { console.log('World!'); }); 

JS小提琴: http : //jsfiddle.net/dashk/5Yz7z/

PS我在我的应用程序中的Backbone.View中使用了这种技术。 这里是Fiddle中代码的片段,以防你在Backbone.js使用它…: http : //jsfiddle.net/dashk/PA6wY/

编辑在Bootstrap 2.3中,您可以指定将添加弹出窗口的目标容器。 现在,您不仅可以执行.parent()定位器,还可以专门监听容器…这可以使侦听器更加具体(想象一下创建一个仅包含弹出窗口的DIV。)

这应该做到这一点。 这将处理使用.popover类在元素内创建的任何现有和将来的按钮元素:

 $('body').on('click', '.popover button', function () { // code here }); 

只是稍微更新DashK的非常好的答案:.delegate()已经被.on()从jQuery 1.7中取代(见这里 )。

 $('a.foo').popover({ html: true, title: 'Hello', placement: 'bottom', content: '' }).parent().on('click', 'button#close-me', function() { console.log('World!'); }); 

请参阅这里的jsfiddle: http : //jsfiddle.net/smingers/nCKxs/2/

我也有一些问题,将.on()方法链接到$(’a.foo’); 如果您遇到此类问题,请尝试将其添加到文档,正文或html中,例如:

 $('a.foo').popover({ html: true, title: 'Hello', placement: 'bottom', content: '' }); $('body').on('click', 'button#close-me', function() { console.log('World!'); }); 

对我有用的非常简单的解决方案是:

 // suppose that popover is defined in HTML $('a.foo').popover(); // when popover's content is shown $('a.foo').on('shown.bs.popover', function() { // set what happens when user clicks on the button $("#my-button").on('click', function(){ alert("clicked!!!"); }); }); // when popover's content is hidden $('a.foo').on('hidden.bs.popover', function(){ // clear listeners $("#my-button").off('click'); }); 

为什么会这样:基本上popover的内容在打开popover之前没有监听器。

当弹出窗口显示时,bootstrap将触发其事件shown.bs.popover 。 我们可以使用jQuery on方法将此事件的事件处理程序附加到$(a.foo) 。 因此,当显示popover时,将调用处理程序(回调)函数。 在此回调中,我们可以将事件处理程序附加到弹出框的内容 – 例如:当用户单击弹出窗口中的此按钮时会发生什么。

关闭popover后,最好删除所有附加的处理程序到popover的内容。 这是通过hidden.bs.popover处理程序完成的,该处理程序使用jQuery .off方法删除处理程序。 当弹出窗口再次打开时,这可以防止弹出窗口中的事件处理程序被调用两次(和更多)…

如果在popover的内容中添加更复杂的结构(例如外部组件),则可能会遇到麻烦。 对于这种情况,这应该可以解决问题。

 var content = $(''); content.on('click', function() { alert('Bingo!') }); $('a.foo').popover({ html: true, content: content }).on('hidden.bs.popover', function() { content.detach(); # this will remove content nicely before the popover removes it }); 

试试这个

 var content = function() { var button = $($.parseHTML("")); button.on('click', '#foo', function() { console.log('you clicked me!'); } ); return button; }; $( '#new_link' ).popover({ "html": true, "content": content, }); 
 $('.btn-popover').parent().delegate('button#close-me','click', function(){ alert('Hello'); }); 

如果在静态html中设置数据属性,则上述方法可以正常工作。 谢谢 :)