简体   繁体   English

包含JavaScript文件时的HTML错误

[英]HTML error when including a JavaScript file

This should not at all be difficult but I can't get a simple JavaScript file included in a flat HTML page. 这一点都不应该很困难,但是我无法在平面HTML页面中包含一个简单的JavaScript文件。

My JavaScript file is as follows: 我的JavaScript文件如下:

<script>
  $(document).ready(function() {
  $('div').css('background', 'red');
 });
</script>

HTML code is as follows: HTML代码如下:

<html>
    <head>
        <script src="js/jquery-1.11.1.min.js"></script>
        <script src="js/init.js"></script>
    </head>
    <title>Song Index!</title>
    <body>
        <div>It's working!</div>
    </body>
</html>

I have confirmed both javascript files are in my js folder. 我已经确认两个javascript文件都在我的js文件夹中。

However, on Chrome I keep getting this error: 但是,在Chrome上,我一直收到此错误:

Uncaught SyntaxError: Unexpected token < init.js:1

Firefox renders a slightly different error: Firefox呈现了一个稍微不同的错误:

SyntaxError: syntax error   <script> init.js (line 1)

I just don't get why it's not working. 我只是不明白为什么它不起作用。

Since you have script in a separate file the <script></script> is not required. 由于您的脚本位于单独的文件中,因此不需要<script></script>

Your script is included within the html page using a script tag, so within your script file js/init.js there should not be the <script> and </script> parts 您的脚本使用script标签包含在html页面中,因此在脚本文件js/init.js中不应包含<script></script>部分

 $(document).ready(function() {
     $('div').css('background', 'red');
 });

JavaScript file should not containc tag. JavaScript文件不应包含c标签。 You javascript should be: 您的JavaScript应该是:

    $(document).ready(function() {
     $('div').css('background', 'red');
   });

Please move your tag in side tag. 请在侧标签中移动您的标签。 HTML code should be: HTML代码应为:

<html>
<head>
    <script src="js/jquery-1.11.1.min.js"></script>
    <script src="js/init.js"></script>
    <title>Song Index!</title>
</head>
<body>
    <div>It's working!</div>
</body>

Simply remove the <script> tags from the external JS file: 只需从外部JS文件中删除<script>标记:

    $(document).ready(function() {
        $('div').css('background', 'red');
    });

First, JS files can't have tags (unless we're talking about injections). 首先,JS文件不能包含标签(除非我们正在谈论注入)。 Second, the title tag has to be in the head tag. 其次, title标签必须在head标签中。

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

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