【问题标题】:jQuery Ui Dialog: how to prevent multiple dialog openings and avoid to limit at just onejQuery Ui Dialog:如何防止打开多个对话框并避免仅限于一个
【发布时间】:2020-08-19 17:15:18
【问题描述】:

我需要使用 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; 
        }
    });
});

【问题讨论】:

  • 为什么不在p.span上添加一个属性,比如data-open,并给它一个值0,当用户点击它时,检查该值是否为0,如果是的,打开modal 并将值更改为1,如果不是,则什么也不做。

标签: jquery user-interface dialog modal-dialog


【解决方案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>

方法二:

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

看看这对你有没有帮助。

【讨论】:

  • 太棒了!但是为什么对话框只打开一次呢?你建议怎么做才能让用户打开它 n 次?
  • 哦等等,您是希望它打开多次还是只打开一次?
  • 我在第一个sn-p中添加了注释,如果要多次打开它,请关注它。
  • 重点是,如果我去掉 off() 函数,那么我可以启动对话框的 n 个实例。一个高于另一个。没有办法管理打开/关闭/打开/关闭/等循环吗?
  • 我认为一旦打开pop-up,后台被禁用,您就不能运行多个实例。查看演示并尝试在pop-up之外点击
猜你喜欢
  • 1970-01-01
  • 2012-11-10
  • 2018-03-23
  • 2011-09-01
  • 2017-01-26
  • 2013-02-09
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
相关资源
最近更新 更多