将JavaScript代码放在单独的文件中不起作用 [英] Putting JavaScript code in a separate file does not work

查看:68
本文介绍了将JavaScript代码放在单独的文件中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Optimizely guiders.js示例代码:

I am working with Optimizely guiders.js example code:

http://jeffpickhardt.com/guiders/

虽然如果我提取JavaScript代码并将其放在单独的文件中,但指南不会加载。

Though if I extract the JavaScript code and place it in a separate file, the guiders do not load.

以下是经过编辑的HTML:

Here is the edited HTML:

<html>
  <head>

    <!-- guider.js requires jQuery as a prerequisite. Be sure to load guider.js AFTER jQuery. -->
    <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
    <script type="text/javascript" src="guider.js"></script>
    <script type="text/javascript" src="guidedTour.js"></script>

    <link rel="stylesheet" href="guider.css" type="text/css" />
  </head>
  <body>
    <span id="clock" style="border: 2px solid #333; width: 300px; height: 200px; text-align: center;" onclick="guider.next();">
      <br />
      <img src="clock.gif" width=150 height=150 />
    </span>


  </body>
</html>

我拥有的所有JavaScript代码guidedTour.js ,在同一目录中。
所有 .js 文件也在同一目录中。并且代码在单独文件中提取之前有效。

I have all the JavaScript code in guidedTour.js, in the same directory. All .js files are also in same directory. And the code worked before extracting it in separate file.

当JavaScript在单独的文件中时,指南不会加载。

The guiders do not load when JavaScript is in separate file.

我在Chrome中收到以下错误:

I am getting the following error in Chrome:


未捕获的TypeError:无法读取null
的属性'clientHeight' jquery-1.5.1.min.js:16

"Uncaught TypeError: Cannot read property 'clientHeight' of null jquery-1.5.1.min.js:16"

尝试更新版本的jQuery会在<$ c $上引发错误C> guiders.js 。
无论如何,这似乎与我将JavaScript代码保存在 index.html 中的行为不同。

Trying a more recent version of jQuery throws an error on guiders.js. Anyway it seems a different behavior than if I keep the JavaScript code in the index.html.

我为工作代码创建了一个jsfiddle:
http: //jsfiddle.net/vpMQy/

I have created a jsfiddle for the working code: http://jsfiddle.net/vpMQy/

我不知道如何在单独的文件中创建一个类似jsfiddle的JavaScript,以便我可以重现问题。

I do not know how to create a similar jsfiddle with the JavaScript in a separate file so that I can reproduce the problem.

是否可以将此JavaScript代码放在单独的文件中?

Is it possible to put this JavaScript code in a separate file?

推荐答案

始终将代码包装在 DOM ready 处理程序中

Always wrap your code inside the DOM ready handler

$(document).ready(function() {
    //your code here
});

或其简写

$(function() {
    //your code here
});

或者将您的脚本放在文档正文

Or put your scripts at the very end of the document's body:

    //...
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="myScript.js"></script>
 </body>

在准备好DOM之前,你不会遇到问题。 =]

And you won't have problems manipulating them DOM before it's ready. =]

这篇关于将JavaScript代码放在单独的文件中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆