首页 > 解决方案 > jQuery Ui Dialog:如何防止打开多个对话框并避免仅限于一个

问题描述

我需要使用 jquery ui 对话框来打开一个对话框并让用户随时打开它。我使用了以下代码,但关键是对话框只能打开一次。我无法再次打开它。代码有什么问题?

$j(document).on("click", "p.span", function () {
 $j('<div></div>').dialog({
        modal: true,
        closeText: 'Close',
        title: "Title",
        open: function () {
            var markup = '<p>Text block</p>';
            $j(this).html(markup);
            $j(document).unbind('click');

    return false; 
        }
    });
});

标签: jqueryuser-interfacedialogmodal-dialog

解决方案


方法一:

$(document).on("click", "p span", function () { // changed p.span to p span(if you're targeting element with class span, you don't need to change this)
 $('<div></div>').dialog({
        modal: true,
        closeText: 'Close',
        title: "Title",
        open: function () {
            var markup = '<p>Text block</p>';
            $(this).html(markup);
            // remove this line if you don't want to limit it only once
            $(document).off('click', 'p span'); // unbind is deprecated, use off instead
        }
    });
});
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p><span>Hola Amigo!</span></p>

方法二:

$(document).on("click", "p span", function () { // changed p.span to p span(if you're targeting element with class span, you don't need to change this)

// Check the default value 
if($(this).attr('data-open') == 0){
  $(this).attr('data-open', 1); // Change the default value
  $('<div></div>').dialog({
        modal: true,
        closeText: 'Close',
        title: "Title",
        open: function () {
            var markup = '<p>Text block</p>';
            $(this).html(markup);
        }
    });
  }
});
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<!-- Add a custom attribute with default value 0 -->
<p><span data-open='0'>Hola Amigo!</span></p>

看看这是否对您有帮助。


推荐阅读