简体   繁体   English

javascript没有在页面加载时执行?

[英]javascript not executing on page load?

in my html: 在我的HTML中:

<head>
<link href="/prop-view.css" media="screen" rel="stylesheet" type="text/css">
        <script src="/javascripts/jquery-1.3.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            var $j = jQuery.noConflict();
        </script>
        <script src="/prop-view.js" type="text/javascript"></script>

in my prop-view.js file: 在我的prop-view.js文件中:

$j("<div class='dk-logo'></div>").appendTo("body");

The inspector shows no errors. 检查员没有显示任何错误。 But the image doesn't show up. 但图像没有显示出来。 It does, however, when I copy and paste that line into the console. 但是,当我将该行复制并粘贴到控制台时。 So... my guess is the js file is running before the document is fully loaded? 所以...我的猜测是在文档完全加载之前js文件正在运行?

Make sure the DOM is loaded first by doing this: 通过执行以下操作,确保首先加载DOM:

$j(function() {
    $j("<div class='dk-logo'></div>").appendTo("body");
});

This is a shortcut for jQuery's ready() function. 这是jQuery的ready()函数的快捷方式。 The code inside is not executed until the <body> tag is fully loaded. <body>标记完全加载之前,不会执行内部代码。

Because you were placing the code before the <body> tag, there was no <body> yet to which to append. 因为你在放置的代码<body>标签,没有<body>还没有哪个追加。

You're right. 你是对的。 Execute your code on DOM ready. 在DOM上准备好您的代码。

$j(document).ready(function(){
  $j("<div class='dk-logo'></div>").appendTo("body");
});

When prop-view.js is executed, the body is not yet available. 执行prop-view.js时,正文尚未可用。 Just attach the script-tags at the bottom of the body-tag. 只需将body-tags附加到body-tag的底部即可。 The page loads faster and the script will run as expected 页面加载速度更快,脚本将按预期运行

<body>
   ...
   <script ...></script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM