This is what I have so far and for some reason the text just doesn't turn blue-->
Testing.html:
<html>
<head>
<script src = "jquery-1.5.min.js" type = "text/javascript"&g开发者_如何学运维t;</script>
<script src = "get_comments.js" type = "text/javascript"></script>
</head>
<body>
<div id = "button">testing this out</div>
</body>
</html>
get_comments.js:
$("#button").css("color","blue");
Looks like you forgot the $
before ("#button").css("color","blue");
$("#button").css("color","blue");
Mistake #1: @dogbert & @wasim caught, you need to use the jQuery factory method of jQuery
(which, by default, is aliased to $
):
$('#button')...
Mistake #2: #button
doesn't exist when get_comments.js
is being executed, so if #1's just a copy-pasta issue, your script still wont work. You'll need to wait for the document to be ready or put the script after the button to select the button:
//this is the jQuery way of setting the document.ready event
//it aliases `jQuery` to `$` in case you ever feel like using `noConflict`
jQuery(function($){
$('#button').css('color', 'blue');
//-or-
$('#button').css({'color':'blue'});
//if you want to set more than one style at a time
});
The $
is a alias to the jQuery()
object. Without the shortcut, what you're trying to do would be written as:
jQuery("#button").css("color", "blue");
With the shortcut:
$("#button").css("color", "blue");
The reason both exist is because other Javascript frameworks and scripts sometimes use the $
so the jQuery()
exists for compatibility.
When your HTML doc is loaded by the browser, the browser starts reading the HTML line after line.
On the 4th line, it's told to load get_comments.js. When it loads get_comments.js, the browser did not yet read the end of the HTML file. So it doesn't know about a DIV called "button".
In the file get_comments.js, you ask the browser to change the font color of a "button" DIV. But as the browser doesn't know yet there will be a "button" DIV in the doc, it doesn't do anything.
To make it work, you have to tell the browser to wait until it finished reading all the HTML page. Than it can tell if there's a "buuton" DIV in the doc, and change it's font color.
to do this, use this code :
// a function to find the button and change its font color
function changeFontColor() {
$('#button').css('color', 'blue');
}
// tell jQuery to execute that function when doc ready
jQuery(document).ready(changeFontColor);
This piece of code can be written in a shorter way :
$(function() { $('#button').css('color', 'blue'); });
Try this one, your JS file is loaded before your HTML body. So you should use .ready();
$(document).ready(function(){
$("#button").css("color","blue");
});
精彩评论