簡體   English   中英

jQuery從單個頁面加載3個div

[英]jQuery load 3 divs from single page

我目前正在通過3個不同的.load()調用加載同一頁面3次。 我想知道是否可以做一些optimize代碼的事情。

當我單擊當前鏈接時,它會將頁面加載3次

$("#"+target).load(url + " #page", function(response, status, xhr){
  if(status === "error")
  {
    $("#"+target).load('error.php?error=503 #page', function(response, status, xhr){
      if(status === "error")
      {
        alert("Something has gone very wrong right now, please contact an admin quoting 'error.php'");
        return;
      }
    }); // This should never fail but if it does kill the page
    console.log('Content failed to load ' + xhr.status + ' ' + xhr.statusText);

    //Force update the title to error
    document.title = "Error";

    $("#pageBreadcrumbs").load('error.php #breadcrumbs');
  }
  else
  {
    console.log('Content was loaded');
    //Load the title dynamically
    document.title = "Venus | " + name;
    $("#pageBreadcrumbs").load(url + ' #breadcrumbs');

    if(sidebar === true)
      $("#pageSidebar").load(url + ' #sidebar');
  }

無論如何,我可以將其縮短為對url或錯誤頁面的1個調用,然后從那里提取出來嗎?

您可以使用以下代碼:

$.get(url, function(response) {
    var $nodes = $(response);

    ... some conditions ...

    var $container1 = $("#"+target).html('');
    $nodes.find('#page').appendTo($container1);

    ... some conditions ...

    var $container2 = $("#pageBreadcrumbs").html('');
    $nodes.find('#breadcrumbs').appendTo($container2);
});

我不確定它是否有效,但是您可以嘗試...

更新

此代碼假定整個服務器響應都包裝在一個容器(div)中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM