我具有要在首次加载网站首页时运行的功能。但是,我不希望该功能运行,因为我到达那里是因为我单击了将我定向到该站点的链接,而不是直接访问该主页。
为此,我将使您进入首页的每个链接都指向home.html#loaded而不是home.html。我还将下面的函数创建为onload执行的函数:

function onloadPreventer(fun) {
    if (window.location.hash != "#loaded") {
        //alert(window.location.hash);
        window.location = window.location + "#loaded";
        //alert(window.location.hash);
        fun;
    };
};

如果fun之后没有#loaded,则此函数应仅执行home.html函数。但是,它总是执行fun
但是,奇怪的部分是它不再再次添加#loaded:

当我第一次进入home.html(不带哈希)时-如果我注释掉alert语句-它首先不给我任何东西,然后给我#loaded然后运行fun。一切都应该如此。
如果我从另一个页面转到home,那么我已经先加载home.html#loaded。该页面不会发出任何警报,onloadPreventer不会在当前位置的末尾添加另一个#loaded但是fun仍然会运行

上面的函数是通过<body>事件从onload标记内部调用的:
<body onload="onloadPreventer(anotherFunction(arg))">

与下面的注释不同,fun确实可以运行。我的问题是,即使页面具有哈希#loadedif语句内的其余代码也不会运行,但fun仍然会运行。

此代码有什么问题?
还有另一种方式(可能更简单)来完成我要完成的工作吗?

最佳答案

似乎您对函数感到困惑:

function foo(){ /* ... */ } /* does NOT call foo */
function bar(){ /* ... */ } /* does NOT call bar */
foo;                        /* does NOT call foo */
foo(arg);         /* DOES call foo with arg as argument  */
foo(bar);         /* does NOT call bar, and DOES call foo with bar as argument */
foo(bar(arg));    /* DOES call bar with argument arg, and DOES call foo
                     with the returned value of bar as argument */

然后,仅当使用括号时,才调用函数。

(或者,您可以使浏览器为您调用函数,例如使它们成为事件处理程序,或者使用setTimeoutsetInterval延迟函数。在这种情况下,您无需使用括号。)

您可以使用
function onloadPreventer(fun) {
    if (location.hash !== (location.hash = "#loaded")) {
        fun(); // DOES call fun
    }
}

但是fun必须是一个函数,而不是函数返回的值:
<body onload="onloadPreventer(
     function(){anotherFunction(arg);} /* does NOT call anotherFunction */
)">

但是最好将脚本与内容分开:
function fun() {
    anotherFunction(arg);
}
document.body.onload = function onloadPreventer() {
    if (location.hash !== (location.hash = "#loaded")) {
        fun(); // DOES call fun
    }
};

10-02 03:47
查看更多