Append jQuery UI dialog to its parent

可紊 提交于 2019-12-11 09:56:25

问题


I have the following html:

<ul id="sortable">
<li class="ui-state-default">1
    <div class="dialog-modal" title="Animal Facts" style="display:none;">
    <p>What is the fastest animal on Earth?</p>
    </div>
  </li>
<li class="ui-state-default">2
<div class="dialog-modal" title="Animal Facts" style="display:none;">
<p>What is the largest animal on Earth?</p>
</div></li>

​ and the following jQuery code:

$( ".dialog-modal" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true
        });

$('.ui-state-default').click(function() {
    $(this).find("div").dialog( "open" );
 });

This does not open the modal dialog on click, what am I missing?

Thanks for the help.


回答1:


This is a current behavior of the jQuery UI dialog.

When defined the jQuery UI dialog is created and appended to the body.

The workaround solution is to append the dialog to its original parent after the creation like:

$(function () {
    $(".dialog-modal").each(function (index) {

        var origContainer = $(this).parent();

        $(this).dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            create: function () {
                $(this).closest('div.ui-dialog')
                    .click(function (e) {
                    e.stopPropagation();
                });
            }
        }).parent().appendTo(origContainer);
    });

    $('.ui-state-default').click(function (event) {
        $(this).find("div").find(".dialog-modal").dialog("open");
    });
});

An important note: look at the create event defined; it's necessary because, the open dialog method executed on the .ui-state-default class elements click is triggered on every click inside the dialog! It's formally correct because now the dialog is contained inside its parent and the click is propagated to the parents with .ui-state-default class. With stopPropagation the problem is solved.

It's a bit hackish, but it works.

Working fiddle: http://jsfiddle.net/IrvinDominin/Avtg9/8/

With the future version of jQuery UI 1.10.0 will be added the option appendTo, to handle this situation without any workaround http://api.jqueryui.com/dialog/#option-appendTo



来源:https://stackoverflow.com/questions/13264201/append-jquery-ui-dialog-to-its-parent

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