2013-03-23 55 views
0

当存在多个链接时,模式对话框的加载次数与链接数一样多。使用多个链接加载外部数据无法正常工作

例如,如果有与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; 
    }); 

回答

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(次),这是极其昂贵的数量。

此外,它在同一次点击中摆脱了多个对话框。

+0

非常感谢您的回复。它与第一个链接工作正常,但它不打开其他链接。 – Efe 2013-03-24 18:20:43

+0

对不起,改变这个:'var url = this.href;'这个'var url = $(this).attr(“href”);'。复制/粘贴,每次都得到我... – MLewisCodeSolutions 2013-03-24 18:40:44

+0

另外我会将这个'$(“#newDialog”)。html(“”);'改为这个'$(“#newDialog”)。html(“”)。 addClass('loading');'在对话关闭事件中。只是注意到它... – MLewisCodeSolutions 2013-03-24 18:48:05