在加载时转到锚点(if else语句)

时间:2012-04-10 14:25:06

标签: javascript anchor onload

您好我有一个使用锚点导航的页面。在加载时,索引页面(A)需要跳转到锚点。很好,我可以使用加载功能,但从页面B回到页面A我想跳转到另一个锚点。我有这个工作:

    <!-- go to Anchor -->
    <script type="text/javascript">

    function goToAnchor() {
    var urllocation = location.href;
    if(urllocation.indexOf("#top") > -1){
        window.location.hash="top";
    } else {
    window.location.hash="middle";
    }
}
    </script>

#middle是来自不包含锚点的链接(或从地址栏中输入地址)时使用的锚点。我想再增加三个'如果'。我在js是相当新的,所以如果我做一些愚蠢的事情,请耐心等待我。我试过这个:

function goToAnchor() {
    var urllocation = location.href;        
if(urllocation.indexOf("#right") > -1){
        window.location.hash="right"; 
    } else {
    window.location.hash="middle";
    }
    if(urllocation.indexOf("#bottom") > -1){
        window.location.hash="bottom"; 
    } else {
    window.location.hash="middle";
    }
    if(urllocation.indexOf("#left") > -1){
        window.location.hash="left"; 
    } else {
    window.location.hash="middle";
    }

但不是快乐,js会破坏,不再在页面加载时进入#middle。

我尝试了外卡方式:

function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#.") > -1){
    window.location.hash=".";
} else {
window.location.hash="middle";
}

}

再一次,没有快乐。

任何帮助请...谢谢

2 个答案:

答案 0 :(得分:1)

如果你只想回到URL中的哈希值,你试过这样的事吗?

var hash = window.location.hash || "middle"; //Get current hash or default to "middle" if no hash is currently set
window.location.hash = +new Date() + ""; //Remove the hash and set it to some random value
window.location.hash = hash; //Set to the old hash

答案 1 :(得分:1)

我不太确定我理解你想要达到的效果(因为window.location.hash应该已经包含了你网址的哈希部分),但你的代码可能应该是

function goToAnchor() {
    var urllocation = location.href;        
    if (urllocation.indexOf("#right") > -1) {
        window.location.hash = "right"; 
    } else if (urllocation.indexOf("#bottom") > -1) {
        window.location.hash = "bottom";
    } else if(urllocation.indexOf("#left") > -1) {
        window.location.hash = "left";
    } else {
        window.location.hash = "middle";
    }
}

我也猜测你的“通配符”方法是用于使用正则表达式:

function goToAnchor() {
    var urllocation = location.href;
    var hashMatch = urllocation.match(/#(.*)/)
    if (hashMatch){
        window.location.hash = hashMatch[1];
    } else {
        window.location.hash = "middle";
    }
}

同样,我不太清楚这段代码应该有什么影响,因为window.location.hash在赋值之前和之后可能会有相同的值。