如何使用window.location存储用户输入URL(锚链接)和重定向用户?

时间:2013-05-21 10:28:26

标签: javascript url input store

我设法创建了一个检测锚链接的条件,但之后如何将锚链接存储在我的anchor_num变量中,以便我可以将使用重定向到特定网址?

<script type="text/javascript">

$(function(){

    if(window.location.hash){

        var anchor_num = "anchorString";
        window.location = "#"+ anchor_num;

    } else 
          {
            //redirect to default page
          }
});

</script>

2 个答案:

答案 0 :(得分:1)

获取:

 var hash = location.hash.slice(1);

设置:

 location.hash = '#' + 'string';

有关更多信息,这个问题可能很有趣:Potential problems setting window.location.hash

答案 1 :(得分:1)

通过附加或更改哈希,浏览器无法刷新页面。在设置了哈希后,您应该调用window.location.reload():

window.location = "#"+ anchor_num;
window.location.reload()