如果使用位置替换,则运行两个条件的JavaScript if语句

时间:2014-06-10 10:24:07

标签: javascript

我有以下if语句在文档就绪时查找哈希值(此代码永远不会在页面上运行)。如果没有散列,则使用replace添加一个,这样它就不会触发hashchange事件。

if( window.location.hash == '' ) {

    console.log('no hash');

    location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange

} else {

    console.log('has hash');

}

但是如果我访问没有哈希的页面,我将在控制台中看到的是has hash并且替换将会发生... 这怎么可能?因为该控制台日志位于语句的不同部分。如果我注释掉替换,那么它只会落入if语句的第一部分。如何跳转到if语句执行替换(但忽略第一个控制台日志)然后跳转到第二部分?

1 个答案:

答案 0 :(得分:1)

你所说的没有意义。

我试图从你的代码中提取一个完整的例子:

<html>
<head>
<script type='text/javascript'>
    function x()
    {
        if( window.location.hash == '' )
        {
            console.log('no hash');
            location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange

            alert('changed!');
        }
        else
        {
            console.log('has hash');
        }
    }
</script>
</head>
<body>
    <button onclick="javascript:x()">test</button>
</body>
</html>

此代码在打开默认值时执行如下:

  1. 点击按钮
  2. 控制台no hash
  3. 警报
  4. 点击按钮
  5. 控制台has hash
  6. 如果你把没有函数声明的代码放在正文中(所以它总是执行),就像这样:

    <html>
    <body>
        <script type='text/javascript'>
            if( window.location.hash == '' )
            {
                console.log('no hash');
                location.replace(location.href.replace(/\/?$/, '#/section-0/page-0')); // change the url without creating a hashchange
    
                alert('changed!');
            }
            else
            {
                console.log('has hash');
            }
        </script>
    </body>
    </html>
    

    它显示:

    1. 控制台no hash
    2. 警报