简单单页面路由跳转demo

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
<div class="result"></div>
</body>
</html>
<script type="text/javascript">
    function Router() {
       // 路由储存
       this.routes = {};
       // 当前路由
       this.currentUrl = '';
    }
    Router.prototype = {
      // 路由处理
      route: function (path, callback) {
        this.routes[path] = callback || function(){};
      },
       // 页面刷新
      refresh: function () {
        // 当前的hash值
        this.currentUrl = location.hash.slice(1) || '/';
        // 执行hash值改变后相对应的回调函数
        this.routes[this.currentUrl]();
      },
      // 页面初始化
      init: function () {
        // 页面加载事件
        window.addEventListener('load', this.refresh.bind(this), false);
        // hash 值改变事件
        window.addEventListener('hashchange', this.refresh.bind(this), false);
      }
    }

    // 全局挂载
    window.Router = new Router();
    // 初始化
    window.Router.init();

    let obj = document.querySelector('.result');

    function changeConent (cnt) {
      obj.innerHTML = cnt
    }

    // 匹配路由做相应的操作
    Router.route('/', function(){
      changeConent("首页");
    })

    Router.route('/item', function(){
      changeConent('item页面');
    })

    Router.route('/list', function(){
      changeConent('list页面')
    })
</script>

 补充: 模拟mvvm的双向数据绑定 

http://hcysun.me/2016/04/28/JavaScript%E5%AE%9E%E7%8E%B0MVVM%E4%B9%8B%E6%88%91%E5%B0%B1%E6%98%AF%E6%83%B3%E7%9B%91%E6%B5%8B%E4%B8%80%E4%B8%AA%E6%99%AE%E9%80%9A%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%8F%98%E5%8C%96/  

原文地址:https://www.cnblogs.com/adouwt/p/7651790.html