【问题标题】:Replace old body element with new loaded element用新加载的元素替换旧的 bo​​dy 元素
【发布时间】:2014-04-30 20:17:40
【问题描述】:

我正在使用 .load() 使用 ajax 加载我的页面内容

我的 html 页面格式如下:

对于我的主页是:

<html>
  <head></head>
  <body class="HOME">
    <header></header>
    <div id="content">
      //CONTENT
    </div>
  </body>
</html>

对于我的文章页面是:

<html>
  <head></head>
  <body class="ARTICLE">
    <header></header>
    <div id="content">
      //CONTENT
    </div>
  </body>
</html>

我只加载 id 为 #content 的 div 元素内的内容。现在,假设我们从文章页面转到主页,此时 body 元素保留旧类 #HOME 我想要的是用包含类 #ARTICLE

编辑:

jQuery('.link').on("click", "a", function() {

 jQuery('body')
    .find("#content")
        .fadeOut(10, function() {

            jQuery('#content').hide('slow').load('/' + " #content", { is_ajaxed_page: "yes" }, function() {

                jQuery('#content').fadeIn(10, function() {

                });
            });
        });

    return false;
}); 

编辑 2: 部分解决。现在,我正在手动设置新类,如下所示: 内容加载后:

jQuery('body').attr('class') = 'HOME';

但是,我想在加载内容时自动检索新正文的类。像这样的:

var newBodyClass = jQuery('body').load('/ body').attr('class');
jQuery('body').attr('class') = newBodyClass;

【问题讨论】:

  • 请分享您的 jQuery 代码。
  • @DerekS 编辑添加 jQuery 代码。
  • 如果要替换整个页面,为什么还要使用 ajax?
  • 您是否尝试过仅更改正文上的类名? document.getElementsByTagName('body')[0].className = 'MYNEWCLASS';
  • @Kyle,我可以这样做,但是如何从加载的 url 中获取新类?

标签: jquery css ajax


【解决方案1】:

确保删除之前的代码。

jQuery('.link').on("click", "a", function() {

 jQuery('body')
    .find("#content")
        .fadeOut(10, function() {

            jQuery('#content').hide('slow').empty().load('/' + " #content", { is_ajaxed_page: "yes" }, function() {

                jQuery('#content').fadeIn(10, function() {

                });
            });
        });

    return false;
}); 

【讨论】:

  • empty() 在里面做什么?刚试了一下,还是返回老班。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
相关资源
最近更新 更多