Jon*_*ood 9 javascript jquery twitter-bootstrap
当用户点击popover外的任何地方时,我正试图隐藏Bootstrap Popover.(我真的不确定为什么Bootstrap的创建者决定不提供这种功能.)
// Hide popover on click anywhere on the document except itself
$(document).click(function(e) {
// Check for click on the popup itself
$('.popover').click(function() {
return false; // Do nothing
});
// Clicking on document other than popup then hide the popup
$('.pop').popover('hide');
});
Run Code Online (Sandbox Code Playgroud)
我觉得困惑的主要是线$('.popover').click(function() { return false; });.这行不为click事件添加事件处理程序吗?这是如何阻止popover('hide')隐藏弹出窗口的调用?
谁有人见过更好的技术?
注意:我之前已经在这里询问过这个问题的变体,但这些问题的答案涉及的代码比上面的代码更复杂.所以我的问题是关于上面的代码
我做了http://jsfiddle.net/BcczZ/2/,希望能回答你的问题
示例HTML
<div class="well>
<a class="btn" data-toggle="popover" data-content="content.">Popover</a>
<a class="btn btn-danger bad">Bad button</a>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
var $popover = $('[data-toggle=popover]').popover();
//first event handler for bad button
$('.bad').click(function () {
alert("clicked");
});
$(document).on("click", function (e) {
var $target = $(e.target),
var isPopover = $target.is('[data-toggle=popover]'),
inPopover = $target.closest('.popover').length > 0
//Does nothing, only prints on console and wastes memory. BAD CODE, REMOVE IT
$('.bad').click(function () {
console.log('clicked');
return false;
});
//hide only if clicked on button or inside popover
if (!isPopover && !inPopover) $popover.popover('hide');
});
Run Code Online (Sandbox Code Playgroud)
正如我在评论中提到的,事件处理程序不会被覆盖,它们只是堆叠.由于.bad按钮上已经有一个事件处理程序,因此它将与任何其他事件处理程序一起被触发
在jsfiddle中打开你的控制台,在页面的某处按下5次(而不是弹出按钮),然后点击bad button你应该看到点击打印的次数与你按下的次数相同
希望能帮助到你
PS:
如果你考虑一下,你已经看到了这种情况,尤其是在jQuery中.想想$(document).ready(...)使用多个jquery插件的页面中存在的所有内容.该行只是在文档的ready事件上注册一个事件处理程序
| 归档时间: |
|
| 查看次数: |
13881 次 |
| 最近记录: |