使用多个链接加载外部数据无法正常工作

时间:2013-03-23 22:35:06

标签: jquery jquery-ui

当有多个链接时,模态对话框的加载次数与链接数一样多。

例如,如果有class="test"的3个链接,当点击第一个链接时,它会在每个链接上加载3次。

无论如何要解决它?

<a href="/user/login/" class="test">comment #1</a><br>
<a href="/user/signup/" class="test">comment #2</a><br>
<a href="/user/reset_password/" class="test">comment #3</a><br>

  $('a.test').click(function() {
        var url = this.href;
        // show a spinner or something via css
        var dialog = $('<div style="display:none" class="loading"></div>').appendTo('body');
        // open the dialog
        dialog.dialog({
            // add a close listener to prevent adding multiple divs to the document
            close: function(event, ui) {
                // remove div with all data and events
                dialog.remove();
            },
            width: 400,
            modal: true
        });
        // load remote content
        dialog.load(
            url, 
            {}, // omit this param object to issue a GET request instead a POST request, otherwise you may provide post parameters within the object
            function (responseText, textStatus, XMLHttpRequest) {
                // remove the loading class
                dialog.removeClass('loading');
            }
        );
        //prevent the browser to follow the link
        return false;
    });

1 个答案:

答案 0 :(得分:0)

试试这个......

<script type="text/javascript">
    $(document).ready(function(e) {
        $('body').append('<div id="newDialog" class="loading"></div>');
        $("#newDialog").dialog({
            close: function(event, ui) {
                $("#newDialog").html("").addClass('loading');
            },
            width: 400,
            modal: true
        });
         $('a.test').click(function() {
            var url = $(this).attr("href");
            $("#newDialog").load(
                url, 
                {},
                function (responseText, textStatus, XMLHttpRequest) {
                    $("#newDialog").removeClass('loading').dialog("open");
                }
            );
            return false;
        });  
    });
</script>

它减少了你必须启动$ .dialog()的次数,这是非常昂贵的。

同样,它也会在同一次点击中删除多个对话框。