location.hash 原生js页面跳转/路由

使用vue开发项目非常方便,vue全家桶让你想实现什么功能都更加便捷,但是使用原生js,jquery开发,页面之间跳转怎么实现呢,

下面说一下window.location.hash,概念性的东西大家看这篇文章,也比较全面,这里主要说下用法:

当前在做的这个项目,页面跳转使用的是hash,基本原理非常简单,在主页面跳转按钮中分别加上一个属性,data,id等都可以,用来标识当前要跳转的页面,然后在点击跳转时获取到data或id属性的值,保存到window.location.hash中,然后根据当前拿到

的data或id的值,即window.location.hash值动态判断要跳转的路径,还有一个很重要的方法,jquery的load()方法,载入远程 HTML 文件代码并插入至 DOM 中,获取到当前要跳转的hash路径,然后执行load方法,载入要跳转的页面即可:

$(".head_mleft ul li").click(function(){ // 导航按钮点击事件
            var index=$(this).index();
            $(this).addClass("head_active").siblings("li").removeClass("head_active");
            $(this).parents(".head_menu").find(".head_mright ul li").removeClass("head_active");
            $(".head_menusleve ul").eq(index).toggle();
            $(".head_menusleve ul").eq(index).show().siblings("ul").hide();
            var sId = $(this).data("href"); // 获取当前点击按钮的data的href属性
            window.location.hash =sId; // 保存到hash中
            self.loadInner(sId); // 页面跳转的方法
            var Iindex=$(".head_menusleve ul").eq(index).find("li").length;
            $(".heaad_secord").css({height:Iindex*70+"%",left:(8+index*7.56+"%")});
        })
loadInner:function(sId){
        var sId = window.location.hash; // 获取到hash值
        var path, index;
        switch(sId) { // 获取与hash值匹配的页面路径
            case "#home":
                path = "home.html";
                break;
            case "#vehicleTrends":
                path = "vehicleTrends.html";
                break;
            ......
        }
        $(".containner").load(path); // 载入页面
    },

还有一个比较重要的方法: data(),可以用来在元素上存放数据,返回的是jquery对象。
data(),load()方法加window.location.hash的综合运用即可实现原生js页面跳转。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值