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

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

问题描述

我正在使用 twitter 引导弹出框,

I am using the twitter bootstrap popovers,

在弹出窗口中我添加了一个按钮,

In the popover I am adding a button,

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

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.

我正在使用自己的按钮版本创建几个弹出框,因此仅将一个类应用于弹出框是行不通的(除非我为每个弹出框生成不同的类:/),按钮可能有也可能没有是自己的ID,所以不能申请ID.

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.

如何将事件处理程序应用到 twitter 引导弹出框的内容中?

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

推荐答案

我遇到了同样的问题,就我而言,$(body).on('click') 解决方法获胜不行,因为应用程序有很多点击按钮.

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 小提琴:http://jsfiddle.net/dashk/5Yz7z/

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

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/

已编辑在 Bootstrap 2.3 中,您可以指定将添加弹出框的目标容器.现在,除了使用 .parent() 定位器,您还可以专门监听容器的事件...这可以使监听器更加具体(想象创建一个仅存在以包含弹出框的 DIV.)

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 引导弹出窗口中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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