Вопрос

I've been following the lessons on Codecademy and I've finished the HTML/CSS and about half of the jQuery tutorials.

I figured I should try to test my knowledge by writing code and opening it in my web browser, which is Chrome (Version 34.0.1847.131 m).

I have the HTML and CSS working perfectly fine, but I can't seem to get the jQuery (script.js is the filename) code to work properly. Here is my code for all three files in my test project:

index.html

<!DOCTYPE html>
<html>  
    <head>
        <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
        <script type='text/javascript' src='script.js'></script>
    </head> 
    <body>
        <div><br/><strong>Click Me!</strong></div> 
    </body>
</html>

stylesheet.css

div
{
    height: 60px;
    width: 100px;
    border-radius: 5px;
    background-color: #69D2E7;
    text-align: center;
    color: #FFFFFF;
    font-family: Verdana, Arial, Sans-Serif;
    opacity: 0.5;
}

script.js

$(document).ready(function()
{   
   $('div').hide();    
});

This code basically should instantly hide a div box I am creating. However, whenever I open the index.html page in chrome, it just shows the box in the upper left corner (thus, my $('div').hide(); isn't being run.

My files are all in the same location:

I'm writing my code in the Sublime Text 2 IDE.

I've seen multiple questions similar to this on SO but everyone's problem was that they have didn't wrap their js code in the $(document).ready() function.

Can someone tell me what I'm doing wrong?

Это было полезно?

Решение

You have not loaded jQuery.

Add this line to your <head>

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

Edit: If you are using this offline, you need to use http:// as it will default to file://

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Hosted by google. Source

Другие советы

try to include the jquery file before your final script

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
...your script....

You need to include jQuery before you include your javascript file, like so:

<head>
    <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script type='text/javascript' src='script.js'></script>
</head> 

You have to attach a jquery library with your page in order to run it.

just add

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

in head section of your html

You need to include jquery library in your html file like this :

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top