jqueryUI:首次点击时初始化对话框内容

时间:2013-03-28 00:18:45

标签: jquery jquery-ui

对于有经验的jqueryUI用户来说,这应该很容易。我想要实现的是:

  • 在页面刚刚渲染时只有一个按钮(仅此而已)
  • 单击此按钮时,将打开一个对话框,并使用AJAX
  • 生成对话框内容

目前我已经掌握了大部分内容,但使用了两个不同的jquery UI按钮。我正在使用icanhaz,但它没有任何区别,因为我得到了这部分工作正常。这是html部分:

<script id="user" type="text/html">
    <p>
        There are following users:
        <ul>
        {{#users}}
            <input type="checkbox" name="user" value="{{ username }}" />{{ fullname }}
            {{^last}}<br />{{/last}}
        {{/users}}
        </ul>
    </p>
</script>

<a id="user-btn" class="btn">show users</a>

<a id="dialog-btn" class="btn">show dialog</a>

<div id="dialog-message" title="Select users">
</div>

这是javascript部分:

$(document).ready( function() {

    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function( response ) {
            var element = $('#dialog-message');
            element.append(ich.user(response));
        });
    });

    $("#dialog-btn").click(function() {
        $("#dialog-message").dialog().dialog("open");
    });
});

当我点击第一个按钮“show users”时,它会生成对话框的内容。单击“显示对话框”时,将创建并打开对话框。我想要清理它 - 在单击时调用ajax(并渲染icanhaz),使用渲染的html创建对话框,打开对话框并显示(只需单击一下)。

1 个答案:

答案 0 :(得分:1)

$(document).ready( function() {

    $("#user-btn").click(function() {
        if ($('#dialog-message').is('.ui-dialog-content')) {
            // data already loaded and dialog already initialized
            $('#dialog-message').dialog('open');
        } else {
            // request data and initialize dialog
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "../php/client/json.php",
                data: {
                    type: "users"
                }
            }).done(function( response ) {
                $('#dialog-message')
                    .append(ich.user(response)) // load data into element
                    .dialog(); // show as dialog (autoOpen is true by default)
            });
        }
    });
});

$('#dialog-message').is('.ui-dialog-content')只是检查对话框是否已在元素上初始化的一种方法;可能有更好的方法。

相关问题