在外部单击时使用 HTML 关闭弹出窗口 [英] Close popover with HTML on click outside

查看:106
本文介绍了在外部单击时使用 HTML 关闭弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Bootstrap Popover 并且 popover 内容是 HTML.我正在使用下面的代码来初始化弹出窗口.此代码基于 https://stackoverflow.com/a/13203876/1354727 这个答案.弹出内容在 div 中,id 为 #song-status-popover.

I am using Bootstrap Popover and popover content is a HTML. I am using below code to initial popover. This code is based on https://stackoverflow.com/a/13203876/1354727 this answer. Popover content is in div with id #song-status-popover.

$(".song-status-link").popover({
            html: true,
            placement: 'bottom',
            content: function () {
                return $("#song-status-popover").html();
            }
});

我想在弹出框外单击时关闭弹出框,因此我使用了以下代码:

I wanted to close the popover when I click outside of popover, so I used below code for that:

$('html').on('mouseup', function (e) {
            if (!$(e.target).closest('.popover').length) {
                $('.popover').each(function () {
                    $(this).closest('div.popover').popover('hide');
                });
            }
});

到目前为止,它运行良好,但我在同时使用这两种代码时遇到了一个问题.当我打开 popover 并单击外部将其关闭时,如果我再次单击链接以打开 popover,它不会在第一次单击时打开.我必须点击两次才能打开它.

Till now it is doing fine, but I am facing one problem with using both code together. When I open popover and click outside to close it, if I again click on link to open popover, it does not get open in first click. I have to click twice in order to open it.

我想知道我缺少什么,以及为什么在通过单击外部关闭弹出窗口后我无法一键打开它.请帮忙!

I want to know what is I am missing and why I am not able to open popover in one click after close it by clicking outside. Please help!

更新:我相信当我在外面点击它会隐藏弹出框,但引导程序仍然认为它是打开的,第一次点击它实际上认为它关闭了,第二次点击它打开弹出框.

UPDATE: I believe that when I click outside it hides popover, but bootstrap still believes that it is open and on first click it actually consider it closed and on second click it open the popover.

推荐答案

试试下面的代码

$('html').on('click', function(e) {
  if (!$(e.target).is('.song-status-link') && $(e.target).closest('.popover').length == 0) {
    $(".song-status-link").popover('hide');
  }
});

http://jsfiddle.net/xzeb91hf/

这篇关于在外部单击时使用 HTML 关闭弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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