Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

javascript - Simple JQuery Script Does Not Work

I am trying to use jQuery for the first time and I am coding it by hand. But my jQuery code doesn't work at all... Here's my setup :

Index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="mainCSS.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="mainJQuery.js"></script>
</head>
    <body>
    <div class="test"> </div>
</body>
</html>

mainCSS.css

.test {
    background-color:#FF0004;
    border-radius:25px;
    display:block;
    height:500px;
    width:500px;
}

mainJQuery.js

// JavaScript Document

$(document).ready(function() {
    $('.test').click(function() {
        $('.test').fadeOut('slow');
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just to state it for the record:

In order for your jQuery code to work, you need to link to the jQuery library in your HTML.

If you are following a tutorial that doesn't include this in the first step, you should find another tutorial to follow. If you got to this question because you did not follow the first step of your tutorial, you should read more carefully before falling back on StackOverflow, or risk getting some serious downvotes.

The two most common ways of including jQuery in your HTML page are:

1) Downloading the library, and linking to a local copy. In your <head> section:

<script type="text/javascript" src="/url/path/to/local/jquery.min.js"></script>

2) Linking to a remote copy of the jQuery on Google's CDN. Again, in <head>:

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

If you don't link to jQuery using one of those options, or something similar, your code will not work. In most browsers you will be able to tell that this is the problem by opening the Javascript console, typing "jQuery" and getting an error like jQuery is not defined.

It's amazing that I couldn't find a duplicate question to close this in favor of, but then again I didn't click on every single "Why doesn't this simple jQuery script work" question on StackOverflow.

And there are a lot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...