I have a jQuery UI Dialog that gets displayed when specific elements are clicked. I would like to close the dialog if a click occurs anywhere other than on those triggering elements or the dialog itself.

Here's the code for opening the dialog:

$(document).ready(function() {
    var $field_hint = $('<div></div>')
        .dialog({
            autoOpen: false,
            minHeight: 50,
            resizable: false,
            width: 375
        });

    $('.hint').click(function() {
        var $hint = $(this);
        $field_hint.html($hint.html());
        $field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
        $field_hint.dialog('option', 'title', $hint.siblings('label').html());
        $field_hint.dialog('open');
    });
    /*$(document).click(function() {
        $field_hint.dialog('close');
    });*/
});

如果我取消注释最后一部分,对话框将永远不会打开.我想这是因为打开对话框的那一次点击又在关闭它.


Final Working Code
Note: This is using the jQuery outside events plugin

$(document).ready(function() {
    // dialog element to .hint
    var $field_hint = $('<div></div>')
            .dialog({
                autoOpen: false,
                minHeight: 0,
                resizable: false,
                width: 376
            })
            .bind('clickoutside', function(e) {
                $target = $(e.target);
                if (!$target.filter('.hint').length
                        && !$target.filter('.hintclickicon').length) {
                    $field_hint.dialog('close');
                }
            });

    // attach dialog element to .hint elements
    $('.hint').click(function() {
        var $hint = $(this);
        $field_hint.html('<div style="max-height: 300px;">' + $hint.html() + '</div>');
        $field_hint.dialog('option', 'position', [$hint.offset().left - 384, $hint.offset().top + 24 - $(document).scrollTop()]);
        $field_hint.dialog('option', 'title', $hint.siblings('label').html());
        $field_hint.dialog('open');
    });

    // trigger .hint dialog with an anchor tag referencing the form element
    $('.hintclickicon').click(function(e) {
        e.preventDefault();
        $($(this).get(0).hash + ' .hint').trigger('click');
    });
});

推荐答案

Check out the jQuery Outside Events plugin

让你做到:

$field_hint.bind('clickoutside',function(){
    $field_hint.dialog('close');
});

Jquery相关问答推荐

如何根据另一个 radio Select 并切换?

jquery如何判断ajax调用的响应类型

为什么我的 toFixed() 函数不起作用?

jQuery 动画滚动

jQuery $.browser 是否已弃用?

可以在不使用for=id的情况下将标签与复选框相关联吗?

在 contenteditable div 中的插入符号处插入 html

jQuery UI 对话框 - 关闭后不打开

根据弹出框相对于窗口边缘的 X 位置更改 Bootstrap 弹出框的位置?

Select 除第一个之外的所有子元素

如何获得元素的正确偏移量? - jQuery

带有 jQ​​uery 的饼图

更改 Eclipse 设置以忽略特定文件上的错误

Isotope 和 Masonry jQuery 插件之间的区别

判断 JS 对象中是否存在键

如何使用 jQuery 或纯 JS 重置所有复选框?

如何使用 JQuery 获取 GET 和 POST 变量?

如何在 JavaScript / jQuery 中获取对象的属性?

你如何记录jQuery中一个元素触发的所有事件?

在jQuery中获取列表元素内容的数组