繁体   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