如何在页面加载时调用 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20929378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:38:22  来源:igfitidea点击:

How To Call A Javascript Function On Page Load

javascriptfunctionhashwindowonload

提问by user3055501

I have this little snippet of code in script tags, along with some functions:

我在脚本标签中有一小段代码,以及一些函数:

window.onload = function()
    {
        if (window.location.hash === 'open')
        {
            $("#signinform").css("display", "block");
            $(".blackout").css("display", "block");
        }
    }

It's not working and I'm pretty sure its just because of a syntax error. However, I can't find it. The function is intended to be called when the page is loaded. Can you guys find the problem?

它不起作用,我很确定它只是因为语法错误。但是,我找不到它。该函数旨在在页面加载时调用。大家能找出问题吗?

回答by kennebec

window.location.hash includes the hash mark ('#').

window.location.hash 包含井号 ('#')。

It will never match 'open', or any string without the hashtag.

它永远不会匹配 'open' 或任何没有主题标签的字符串。

回答by Josh Beam

Try this:

试试这个:

if (window.location.hash === '#open')

The hashmember of window.locationwill return the #sign, plus whatever string follows it.

window.location散列成员将返回#符号,加上它后面的任何字符串。

You can detect this behavior by typing console.log(window.location.hash)into your console.

您可以通过在控制台中键入console.log(window.location.hash)来检测此行为。

Additionally, since you are already using jQuery, you could potentially stick with:

此外,由于您已经在使用 jQuery,您可能会坚持使用:

$(function() {

instead of

代替

window.onload

回答by Edgar Villegas Alvarado

As you are using jquery, you can do:

当您使用 jquery 时,您可以执行以下操作:

$(document).ready(function(){
    if (window.location.hash === '#open')  //Inlude hash here!
    {
        $("#signinform").css("display", "block");
        $(".blackout").css("display", "block");
    }
});

window.locationalso works, but it takes much longer, for example if you have big images in your page, it will wait until all are loaded. $(document).readydoesn't have this problem.

window.location也可以,但需要更长的时间,例如,如果您的页面中有大图像,它会等到所有图像都加载完毕。$(document).ready没有这个问题。

Cheers

干杯

回答by Sergei Zahharenko

working just fine:

工作得很好:

function loaded() {
    if (window.location.hash == '#open') alert('ok');
}
window.location.hash = 'open'
window.onload = loaded;

http://jsfiddle.net/acrashik/NEfR2/481/

http://jsfiddle.net/acrashik/NEfR2/481/

回答by Lucas Serafim

Are you using jquery right? Try using .ready(); http://api.jquery.com/ready/

你使用 jquery 对吗?尝试使用 .ready(); http://api.jquery.com/ready/

A good way to write javascript is put all your javascript code on end of your page, before </body>

编写 javascript 的一个好方法是将所有的 javascript 代码放在页面的末尾,然后 </body>