CS计算机代考程序代写 javascript chain Java jquery Hive jQuery Tutorial

jQuery Tutorial

Copyright Ellis Horowitz 2012-2021 1

What is jQuery?

• A framework for client-side JavaScript.
• Frameworks provide useful alternatives for

common programming tasks.
• An open source project at jquery.com
• It simplifies
– HTML document traversing
– Event Handling
– Animating
– AJAX interactions

Copyright Ellis Horowitz 2012-2021 2

jquery.com

What is available with jQuery?

• Cross browser support
and detection

• AJAX functions
• CSS functions
• DOM manipulation
• DOM transversal
• Attribute manipulation
• Event detection and

handling

• JavaScript animation
• Hundreds of plugins for

pre-built user
interfaces, advanced
animations, form
validation, etc

• Expandable
functionality using
custom plugins

• Small foot print

Copyright Ellis Horowitz 2012-2021 3

Downloading jQuery

• Installation – You just download the latest
jquery-x.y.z.js file and put it in your website
folder

• http://jquery.com/download
• jQuery is lightweight: 90KB (minified and

uncompressed), 33KB (Minified and Gzipped)
• Latest version is 3.6.0

Copyright Ellis Horowitz 2012-2021 4

http://jquery.com/download

So How Does jQuery Change How You Write
JavaScript?

• jQuery adds a JavaScript object called $ or jQuery
to your JavaScript code.
– Through manipulation of this JavaScript code, it

abstracts away commonly used JavaScript objects into
$ and jQuery, such as the DOM (document),
XMLHTTPRequest, and JSON

• Example: Instead of
var myButton = document.getElementById(“myButton”);

• In jQuery, it’s just
$(“#myButton”);

Copyright Ellis Horowitz 2012-2021 5

jQuery Basic Selectors
• These are examples of “Basic” selectors, based on CSS1:
• All Selector (“*”): selects all elements, sets css properties and returns the

number of elements found
var elementCount = $(“*”).css(“border”, “3px solid red” ).length;

• Class Selector (“.class”): selects all elements with a given class and sets css
properties

$(“.myClass”).css(“border”, “3px solid red”);

• Element selector (“element”): selects all elements with the given tag name,
e.g. div, and sets css properties

$(“div”).css(“border”, “9px solid red”);

• ID selector (“#id”): selects a single element with the given id attribute
$(“#myDiv”).css(“border”, “3px solid red”);

• Multiple selector (“selector1, selector2, selectorN”): selects a combined
result of all the specified selectors

$(“div, span, p.myClass”).css(“border”, “3px solid red”);
• For more examples see: http://api.jquery.com/category/selectors/basic-css-selectors/

Copyright Ellis Horowitz 2012-2021 6

http://api.jquery.com/category/selectors/basic-css-selectors/

Other jQuery Selector Categories
• JQuery borrows notation from CSS1-3 “selectors”, as a tool to match a set of

elements. Here are some examples of what one can do:
• Attribute: selects elements that have the specified attribute and changes

the associated text
$(“input[value=’Hot Fuzz’] “). text( “Hot Fuzz” ) ;

• Basic Filter, e.g. selects all elements that are h1, h2, h3, etc and assigns css
properties
$(“:header”).css({ background: “#ccc”, color: “blue” });

• Child Filter, e.g. finds the first span in each div and underlines the text
$(“div span:first-child”).css( “text-decoration”, “underline” )

• Content Filter, e.g. finds all div containing “John” and underlines them
$(“div:contains(‘John’)”).css( “text-decoration”, “underline” );

• Form, e.g. finds all buttons and adds the css class “marked” to their
properties
var input = $(“:button”).addClass( “marked” );

• For more examples see: http://api.jquery.com/category/selectors

Copyright Ellis Horowitz 2012-2021 7

http://api.jquery.com/category/selectors

jQuery Functions
• Either attached to the jQuery object or chained off of a selector

statement.
– E.g., Run a function when the page is fully loaded

$( window ).load(function() {

//run code
} );

• Most functions return the jQuery object they were originally passed, so
you can perform many actions in a single line.
– E.g., Add the class bigImg to all images with height > 100 once the

image is loaded
$(“img.userIcon” ).load(function() {

if ( $( this ).height() > 100 {
$( this ).addClass(“bigImg”);

}
});

• The same function can perform an entirely different action based on the
number and type of parameters.

Copyright Ellis Horowitz 2012-2021 8

More jQuery Examples

• Remember these examples?
http://csci571.com/examples.html#dom

• We’ll revisit the examples, but with jQuery
instead!
https://csci571.com/examples.html#jquery

Copyright Ellis Horowitz 2012-2021 9

Example 1:
document.getElementById.style.color

hex=255 // Initial color value.
function fadetext() {
if(hex>0) { //If color is not black yet

hex -= 11; // increase color darkness

document.getElementById(“sample”).style.color=”rgb(“+hex+”,”+h
ex+”,”+hex+”)”;

setTimeout(“fadetext()”,20); }
else hex=255 //reset hex value

}

JavaScript w/o jQuery

http://csci571.com/examples/dom/ex1.html

Copyright Ellis Horowitz 2012-2021 10

Example 1: $.fadeOut(), $.delay(), $.fadeIn()

$(function() { // when document is ready
$(“#fadeText”).click(function() { // set a onClick handler on fadeText

$(“h3”).fadeOut(125).delay().fadeIn(125);
// fadeOut the h3 for 125 ms, delay, then fadeIn

});
});

JavaScript with jQuery

http://csci571.com/examples/jquery/dom/ex1.html

Copyright Ellis Horowitz 2012-2021 11

Example 2: document.getElementsByTagName

function handleAllTags()
{ var arrayOfDocFonts;

if (document.all || document.getElementById) {
arrayOfDocFonts = document.getElementsByTagName(“font”);
alert(“Number of font tags in this document are ” + arrayOfDocFonts.length + “.”);

}
else

document.write(“Unrecognized Browser Detected”); }
}

JavaScript w/o jQuery

http://csci571.com/examples/dom/ex2.html

JavaScript w/ jQuery
$(function() {// when document is ready

$(“#countTags”).click(function() { // when countTags is clicked,
alert(“Number of font tags in this document are ” + $(“font”).length);
// alert the number of font tags in the HTML

});
});

http://csci571.com/examples/jquery/dom/ex2.html
Copyright Ellis Horowitz 2012-2021 12

Example 3:
document.getElementById().innerHTML

var hits = 0;
function updateMessage() {

hits += 1;
document.getElementById(“counter”).innerHTML = “Number of clicks = ” + hits; }

JavaScript w/o jQuery

http://csci571.com/examples/dom/ex3.html

$(function() {
var hits = 0;
$(“#updateMessage”).click(function() {

$(“#counter”).html(“Number of clicks = ” + ++hits);
});

});

JavaScript w/ jQuery

http://csci571.com/examples/jquery/dom/ex3.html

Copyright Ellis Horowitz 2012-2021 13

Example 4:
document.getElementById().style.left

JavaScript and HTML w/o jQuery

http://csci571.com/examples/dom/ex4.html
Copyright Ellis Horowitz 2012-2021 14





Example 4: $.css();

JavaScript and HTML w/ jQuery

http://csci571.com/examples/jquery/dom/ex4.html
Copyright Ellis Horowitz 2012-2021 15




Example 5: document.getElementById(),
parseint()

JavaScript w/o jQuery

http://csci571.com/examples/dom/ex5.html

JavaScript w/ jQuery

Copyright Ellis Horowitz 2012-2021 16

http://csci571.com/examples/jquery/dom/ex5.html

$(function() {
$(“#counter1”).click(function() {

$(“#counter1”).css(“left”,(parseInt($(“#counter1”).css(“left”))+50)+”px”);
});

});

var obj = document.getElementById(‘counter1’);
var xlocation = parseInt(obj.style.left);
function handleClick( ) {

xlocation += 50;
document.getElementById(‘counter1’).style.left = xlocation + “px”;}

Example 6: Uses childNodes, removechild,
appendChild

function reverse(n)
{ // Reverse the order of the children of Node n
var kids = n.childNodes; // Get the list of children
var numkids = kids.length; // Figure out how many children there are
for(var i = numkids-1; i >= 0; i–) { // Loop backward through the children

var c = n.removeChild(kids[i]); // Remove a child
n.appendChild(c); // Put it back at its new position

} }

JavaScript w/o jQuery

http://csci571.com/examples/dom/ex6.html

Copyright Ellis Horowitz 2012-2021 17

Example 6: $.children(), $.remove(),
$.append();

var onReady = function() {
$(“.reverse”).on(“click”, function() {

var kids = $(“body”).children();
for(var i = kids.length – 1; i >= 0; i–) {

var c = $(kids[i]).remove();
$(“body”).append(c);

}
onReady();

});
}

$(onReady);

JavaScript w/ jQuery

http://csci571.com/examples/jquery/dom/ex6.html

Copyright Ellis Horowitz 2012-2021 18

Example 4b: Uses innerHTML

function setInnerHTML(nm, value) {
if (nm == ”) return;
var

element=document.getElementById?document.getElementById(nm):(document.all?document.all(nm):nu
ll);
if (element) {

if(element.innerHTML) {
element.innerHTML=value;

}
else notSupported( );

}
else NotSupported( );

}

JavaScript w/o jQuery

http://csci571.com/examples/dom/domtest.html
Copyright Ellis Horowitz 2012-2021 19

Example 4b: $.change() and $.html();

$(function() {
$(“#sel”).change(function() {

var selector = “#” + $(“#sel”).val();
$(selector).html($(“input[name=’t’]”).val());

});
});

JavaScript w/ jQuery

http://csci571.com/examples/jquery/dom/ex4b.html

Copyright Ellis Horowitz 2012-2021 20

jQuery & AJAX

• jQuery has a series of functions which provide
a common interface for AJAX, no matter what
browser you are using.

• Most of the upper-level AJAX functions have a
common layout:
– $.func(url[,params][,callback]), [ ] optional
• url: string representing server target
• params: names and values to send to server
• callback: function executed on successful

communication.

Copyright Ellis Horowitz 2012-2021 21

jQuery AJAX load method

• The load() method loads data from a server and puts the
returned data into the selected element.

• $(selector).load(URL,[data,callback]);
• The selector is a usually a reference to div or span tag
• The required URL parameter specifies the URL you wish to load.
• The optional data parameter specifies a set of querystring

key/value pairs to send along with the request.
• The optional callback parameter is the name of a function to be

executed after the load() method is completed.
• For examples see
http://csci571.com/ajaxexamples/simple/simpleajaxexjquery.html
or http://csci571.com/examples.html#jquery [4 examples under Ajax]

Copyright Ellis Horowitz 2012-2021 22

http://csci571.com/ajaxexamples/simple/simpleajaxexjquery.html
http://csci571.com/examples.html

AJAX Example 1




Let jQuery AJAX
Change This Text


Copyright Ellis Horowitz 2012-2021 23

AJAX Example 2

Let jQuery AJAX
Change This Text

Note: non-jQuery version of .ready:

document.addEventListener(“DOMContentLoaded”,
function(event) { //do work });

Copyright Ellis Horowitz 2012-2021 24

AJAX Example 3 – GET Method



Copyright Ellis Horowitz 2012-2021

The $.get() method requests data from the server
with an HTTP GET request.
The required URL parameter specifies the URL you wish to
request.
The optional callback parameter is the name of a function
to be executed if the request succeeds.
The following example uses the $.get() method to retrieve
data from a file on the server

25

AJAX Example 4 – POST Method



Copyright Ellis Horowitz 2012-2021 26

Summary jQuery AJAX Functions

• $.func(url[,params][,callback])
– $.get
– $.getJSON
– $.getIfModified
– $.getScript
– $.post

• $(selector), inject HTML
– load
– loadIfModified

• $(selector), ajaxSetup alts
– ajaxComplete
– ajaxError
– ajaxSend
– ajaxStart
– ajaxStop
– ajaxSuccess

• $.ajax, $.ajaxSetup
– async
– beforeSend
– complete
– contentType
– data
– dataType
– error
– global
– ifModified
– processData
– success
– timeout
– type
– url

Copyright Ellis Horowitz 2012-2021 27

• jQuery way of a mouseover event that shows a
submenu when menu is selected:

$(‘#menu’).mouseover(function() { // Anonymous function
$(‘#submenu’).show();

});

jQuery Usage Example (1) – Event

Copyright Ellis Horowitz 2012-2021 28

• Stopping a normal event action: Suppose we
want to stop the action of following a URL when a
link is clicked. The action is part of the event
object. We can reference the event object and
call .preventDefault();

$(‘#menu’).click(function(evt){
//JS code here
evt.preventDefault();

}

jQuery Usage Example (2) – Event

Copyright Ellis Horowitz 2012-2021 29

• Selecting all form elements of a certain type:
$(‘:text’) It selects all text fields.

• Use with :input ( all form elements), :password, :radio,
:checkbox, :submit, :image, :reset, :button, :file,
:hidden
See https://api.jquery.com/category/selectors/form-

selectors/
• Set the value of a form element

Var fieldvalue = $(‘#total’).val(Yourvalue);
See https://api.jquery.com/val/

jQuery Usage Example (3) – Form Selectors

Copyright Ellis Horowitz 2012-2021 30

https://api.jquery.com/category/selectors/form-selectors/

• Determining if checkbox is checked

If ($(‘#total’).attr(‘checked’)) {
//Do whatever you want if box is checked

}
else {

//Do whatever you want if box is not checked
}

jQuery Usage Example (4) – Attribute

Copyright Ellis Horowitz 2012-2021 31

• Form Events such as submit:

$(document).ready(function() {
$(‘#signup’).submit(function() {

if ($(‘#username’).val() ==‘’) {
alert (‘Please supply name to name

field’);
return false;

}
})

});

jQuery Usage Example (5) – Form Events

Copyright Ellis Horowitz 2012-2021 32

• Focus Example: Auto erases default text in a
field when it gets the focus

$(‘#username’).focus(function() {
var field = $(this);
if(field.val()==field.attr(‘defaultValue’)) {

field.val(‘’);
}

});

jQuery Usage Example (6) – More events

Copyright Ellis Horowitz 2012-2021 33

• Click: If any radio button is clicked
$(‘:radio’).click(function() {

//do stuff
});

• Add focus to the first element of the form:
$(‘username’).focus;

jQuery Usage Example (7)

Copyright Ellis Horowitz 2012-2021 34

Is jQuery Worth It?
Yes No

Good use of the jQuery library will
make it worthwhile in your code; will
make JavaScript more readable and
understandable

Bad use of jQuery library adds extra overhead.
Why even add jQuery?
Remember you need to add:

If web application requires a lot of
DOM manipulation, hiding elements,
fading out elements, etc

Doesn’t even need DOM manipulation; could be
done with CSS

Cross Browser Support – no need extra
code for browser compatibility

Audience only uses Firefox – no need cross
browser support only

Copyright Ellis Horowitz 2012-2021 36

jQuery

• It’s a useful library when used wisely.
• It will allow you to write JavaScript differently
– Write less, do more.

• Remember: jQuery is just JavaScript
– What you can do with jQuery, you can always do

without jQuery but with more code.

Copyright Ellis Horowitz 2012-2021 37

jQuery Resources

• Project website
– http://www.jquery.com

• Learning Center
– http://docs.jquery.com/Tutorials
– http://www.learningjquery.com/

• Support
– http://docs.jquery.com/Discussion
– http://www.nabble.com/JQuery-f15494.html mailing list archive
– irc.freenode.net irc room: #jquery

• Documentation
– http://docs.jquery.com/Main_Page
– http://www.visualjquery.com
– http://jquery.bassistance.de/api-browser/

• jQuery Success Stories
– http://docs.jquery.com/Sites_Using_jQuery

• jQuery selectors Demo
– https://api.jquery.com/category/selectors/

Copyright Ellis Horowitz 2012-2021 38

http://www.jquery.com/
http://docs.jquery.com/Tutorials
http://www.learningjquery.com/
http://docs.jquery.com/Discussion
http://www.nabble.com/JQuery-f15494.html
http://irc.freenode.net/
http://docs.jquery.com/Main_Page
http://www.visualjquery.com/
http://jquery.bassistance.de/api-browser/
http://docs.jquery.com/Sites_Using_jQuery
https://api.jquery.com/category/selectors/