0

I'm just learning about html, css, and javascript through codeacademy. I wanted to try and practice what I learned by creating a website without the codeacademy environment. The problem I'm having is linking my javascript to my html. I have three files in a folder: index.html, style.css, and script.js. I'm setting it up just as I learned, the website is loading fine, but the javascript never works for some reason. Any reason why? Here's my html and js:

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Result</title>
    <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
    <script type='text/javascript' src='script.js'></script>
</head>
<body>
    <form>
    MESSAGE: <input type="text" name="message" value="Type your text here!">
    </form>
    <button>Add!</button><br/>
    <div id="messages"></div>
</body>

script.js:

$(document).ready(function () {
    $('button').click(function () {
        var toAdd = $("input[name=message]").val();
        $('#messages').append("<p>" + toAdd + "</p>");
    });
});
4

5 回答 5

9

You need to include jquery (before including your script.js)

<head>
    <title>Result</title>
    <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></script>
    <script type='text/javascript' src='script.js'></script>
</head>
于 2013-06-10T14:50:18.613 回答
3

You haven't included jQuery, codecademy does this for you, you can either download a local file here, then include it like your script.js:

<script src="jquery.js"></script>

or just link to the CDN like this:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></script>
于 2013-06-10T14:50:43.850 回答
1

Your script is written using jQuery syntax, but you have not included the jQuery library anywhere. Add jQuery before your script and you should be fine.

I would recommend using a CDN. Add this line just before your script tag:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></script>

Edit: At sircapsalot's behest, a CDN is a Content Delivery Network. Read why using a CDN is a good idea.

于 2013-06-10T14:50:33.877 回答
1

You have to reference the actual JQuery lib as well:

Add this before your script:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
于 2013-06-10T14:50:48.227 回答
0

正如在此之前的答案中提到的那样。您应该首先像这样包含您的 jQuery:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

但这里有一个提示。每当您在网页中包含 jQuery 时,您都应该首先下载它,然后再包含它。这将为您带来好处,即使用户失去他/她的互联网连接,jQuery 仍然可以工作,但另一方面,如果您从 Google API 中包含它,脚本将在他/她失去互联网连接时停止工作。

你可以在这里下载 jQuery:http: //jquery.com/download/

您可以通过这种方式包含它(取决于您保存它的名称):

<script src="jquery.js"></script>
于 2013-06-10T17:25:06.200 回答