将事件处理程序附加到twitter bootstrap popover中的按钮 [英] Attach event handler to button in twitter bootstrap popover

查看:102
本文介绍了将事件处理程序附加到twitter bootstrap popover中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在popover中,我正在添加一个按钮,



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



我正在使用自己的版本的按钮创建几个popovers,所以只需应用类别到popover将无法工作(除非我为每个类别生成不同的类:/),该按钮可能有也可能没有自己的ID,因此不能应用ID。



/ p>

解决方案

我有过这样的一个事件处理程序同样的问题,在我的情况下,由于应用程序有很多按钮,所以 $(body).on('click')解决方法将无法正常工作。 p>

我做了这样的事情g代替。这样,我们可以将代理事件的范围限制在popover元素的父级。

  $('a。 foo')popover({
html:true,
title:'Hello',
placement:'bottom',
content:'< button id = me关闭我!< / button>'
})。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/



EDITED
Bootstrap 2.3,您可以指定将要添加的popover的目标容器。现在,而不是执行.parent()定位器,您也可以专门侦听容器的事件...这样可以使侦听器更具体(想象一下创建一个仅存在于包含popover的DIV。)


I am using the twitter bootstrap popovers,

In the popover I am adding a button,

I need to attach a click handler to the button, but the way popover works is each time it shows it removes and re-creates the element, instead of just showing/hiding it, hence removing any event handlers I have associated with said button.

I am creating several popovers all with their own version of the button, so just applying a class to the popover won't work (unless I generate a different class for each one :/), the button may or may not have it's own ID, so cannot apply an ID.

How can I apply a event handler to something in the contents of the twitter bootstrap popover?

解决方案

I had the same problem, and, in my case, the $(body).on('click') workaround won't work, since the application has lotta click buttons.

I did the following instead. This way, we can limit the scope of the delegate event to just the parent of the popover element.

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

JS Fiddle: http://jsfiddle.net/dashk/5Yz7z/

P.S. I used this technique in within a Backbone.View in my application. Here's the snippet of the code in Fiddle, in case you're using this in Backbone.js as well...: http://jsfiddle.net/dashk/PA6wY/

EDITED In Bootstrap 2.3, you can specify a target container which popover will be added to. Now, instead of doing the .parent() locator, you can also listen to events specifically to the container... This can make the listener even more specific (Imagine creating a DIV that only exists to contain the popover.)

这篇关于将事件处理程序附加到twitter bootstrap popover中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆