2013-03-23 26 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