前端简单实现路由


<input type="text" id=name />
<button>indexbutton>
  <button>listbutton>
  <h1>Hash模式的前端路由h1>
  <div id="router">div>
 
  <script>
    window.addEventListener('load', function () {
      var btn = document.getElementsByTagName('button')
      
      var router = document.getElementById('router')
 
      //配置路由路径
      var routers = [
        { path: '/index', component: '

我是首页

' }, { path: '/list', component: '

我是列表页

' } ]; //初始化路由 window.location.hash = '/' //点击设置路由跳转到首页 btn[0].onclick = function () { window.location.hash = '/index' } //点击设置路由跳转到列表业 btn[1].onclick = function () { window.location.hash = '/list' } window.addEventListener('hashchange', function () { var name=document.getElementById('name').value var hash = window.location.hash // for (var i = 0; i < routers.length; i++) { // if (name==="hasagei"&&hash==="#/index"&&) //{ // router.innerHTML = routers[i].component //} if (name==="hasagei"&&hash==="#/index"){ router.innerHTML="

我是首页

" }else{ router.innerHTML="

你没权限

" window.location.hash = '#/' } }) }) script>