jQuery Ui Dialog: how to prevent multiple dialog openings and avoid to limit at just one

微笑、不失礼 提交于 2020-05-17 07:02:08

问题


I need to use jquery ui dialog in order to open a dialog and let users open it anytime they want. I used the following code but the point is that the dialog can open just once. I cannot open it a second time. What's wrong with the code?

$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; 
        }
    });
});

回答1:


Method 1:

$(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>

Method 2:

$(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>

See if this helps you.



来源:https://stackoverflow.com/questions/61606453/jquery-ui-dialog-how-to-prevent-multiple-dialog-openings-and-avoid-to-limit-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!