正文内容必须更新,无需更改页眉和页脚,也无需刷新页面

问题描述 投票:0回答:3

我有一个标题菜单,其中包含“主页”和“关于我们”按钮。默认情况下加载主页。在主页中,我在主页中有一个链接。当我单击主页上的链接或“关于我们”按钮时,必须在主页中更改正文内容,但不应刷新页面。必须显示“关于我们”相关数据。页眉和页脚页面对于所有页面都是通用的,只需更新正文内容而无需刷新页面。我不想在这里使用任何 jquery 或没有服务器调用。

javascript html angular angular2-routing
3个回答
0
投票

您正在寻找的是路由器。请参阅有关路由和导航的官方 Angular 2 文档,以获得有关此主题的更详细信息。

我已经设置了一个 Plunker,为您提供 Angular 2 中路由的基本示例。

路由发生在一个名为

app.routing.ts
的新文件中,重要部分请参见下文:

import { HomeComponent }  from './home.component';
import { AboutUsComponent }    from './aboutus.component';

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'aboutus', component: AboutUsComponent }
];

首先导入要导航到的组件(如页面),然后设置其导航到的路径(如地址栏中的 url)。导航至 foo.com/aboutus 时,

path: 'aboutus', component: AboutUsComponent
将加载
AboutUsComponent

在 HTML 中,主要的变化是您不使用

<a href="/aboutus">
,而是使用
<a routerLink="/aboutus"</a>
,因此 Angular 知道导航到哪里(请参阅下面的代码)。

<nav>
  <a routerLink="">Home</a>
  <a routerLink="/aboutus">About us</a>
</nav>

尝试代码并查看文档以便掌握其中的窍门。


0
投票

您可以为此使用ajax:

$("#link1").click(function(){
    $.ajax({
        url: url, //get the url of the link
        type: post,
        success: function(result){
            // Arrange your data according to your html webpage 
            // If the result is already aligned as per your structure then directly put it into the div you want to replace the content
            $("#container").empty();
            $container.append(arrangedHtmlStructure);
        }
    })

})

0
投票

function show (pagenum) {
  $('.page').css('display','none');
   if (pagenum == 0 ) {
      $('.home').css('display','block');
   }
   if (pagenum == 1 ) {
      $('.about').css('display','block');
   }
}
.header,.footer {
   background: black;

}
.menu a{
      color: white;
}

.about {
   display : none
}

.footer {
 position : fixed;
  bottom:0;
  width:100%;
  color:white;
  text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
         <div class="header">
              <ul class="menu">
                  <li>
                      <a href="#" onclick="show(0)" >Home</a>
                                          <a href="#" onclick="show(1)" >About Us</a>
                  </li>
              </ul>
         </div>
         <div class="home page" >This is Home</div>
         <div class="about page">This is About</div>
          <div class="footer">This is footer</div>
  </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.