温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.muo.com/tag/basic-guide-jquery-javascript-programmers/
点击访问原文链接

A Basic Guide to JQuery for Javascript Programmers

A Basic Guide to JQuery for Javascript Programmers Menu Sign in now Close PC & Mobile Submenu Windows2 Linux Android Apple Technical Submenu Tech Explained Security Software Submenu Productivity Internet Creative Screen Submenu Entertainment Streaming Home Submenu Smart Home Home News Sign in Newsletter Menu Follow Followed Like More Action Sign in now Productivity Android Smart TVs Networking Windows 11 Entertainment Close
A Basic Guide to JQuery for Javascript Programmers guide-jquery-js By  Joe Coburn Published Dec 6, 2016, 6:00 PM EST Joe is a graduate in Computer Science from the University of Lincoln, UK. He's a professional software developer, and when he's not flying drones or writing music, he can often be found taking photos or producing videos. Sign in to your MakeUseOf account

JQuery is one of the most popular JavaScript libraries on the planet (what is JavaScript). At the time of it's inception, JavaScript (will be referred to as JS from here on in) was in a very different place. January 14th 2006 was the day when jQuery was announced at BarCampNYC. JS was still lacking somewhat -- browsers all supported parts of it, but lots of hacks and workarounds had to be implemented for compliance.

JQuery came along and changed everything. JQuery made it very easy to write browser compliant code. You could animated webpages without having a degree in computer science -- hooray! Ten years on, is jQuery still king, and if you have never it used it before, what can you do with it?

In addition to brushing up on your JavaScript skills, you may want to read some HTML and CSS tutorials first if you are not familiar with them either.

We have introduced jQuery before, so this guide to JQuery will focus on actually coding.

Getting Started

You may be familiar with the JS way of selecting ids from the Document Object Model (DOM):

document.getElementById('foo');

Well JQuery takes this one step further. You don't have to call different methods to select classes, ids, or multiple elements. Here's how you select an id:

$('#bar');

Easy right? It's exactly the same syntax to select almost any DOM element. Here's how you select classes:

$('.baz');

You can also get creative for some real power. This selects all td elements inside a table except the first one.

$('table td').not(':first');

Notice how the selector names match almost exactly their CSS counterparts. You can assign objects to regular JS variables:

var xyzzy = $('#parent .child');

Or you can use jQuery variables:

var $xyzzy = $('#parent .child');

The dollar sign is solely used to signify that this variable is a jQuery object, something that is very helpful on complex projects.

You can select the parent of an element:

$('child').parent();

Or the siblings:

$('child').siblings();

You need to execute your code once the browser is ready. Here's how you do that:

$(document).ready(function() {
console.log('ready!');
});
More Power

Now that you know the basics, let's move on to some more complex stuff. Given an html table:


Make
Model
Color


Ford
Escort
Black


Mini
Cooper
Red


Ford
Cortina
White

Say you want to make every other row a different color (known as Zebra Stripes). Now you could use CSS for this:

#cars tr:nth-child(even) {
background-color: red;
}

This is how that could be achieved with jQuery:

$('tr:even').addClass('even');

This will achieve the same thing, providing that even is a class defined in CSS. Notice how the full stop before the class name is not needed. These are usually only required for the main selector. Ideally, you would use CSS for this to begin with, although it's not a big deal.

JQuery can also hide or remove rows:

$('#fordCortina').hide();

$('#fordCortina').remove();

You do not have to hide an element before removing it.

Functions

JQuery functions are just like JS. They use curly braces and can accept arguments. Where it gets really interesting is through callbacks. Callbacks can be applied to almost any jQuery function. They specify a piece of code to run once the core action is completed. This provides huge functionality. If they did not exist, and you wrote your code expecting it to run in a linear fashion, JS would continue to execute the next line of code while waiting for the previous one. Callbacks ensure the code only runs once the original task is complete. Here's an example:

$('table').hide(function(){
alert('MUO rules!');
});

Be warned -- this code executes an alert for every element. If your selector is something on the page more than once, you will get multiple alerts.

You can use callbacks with other arguments:

$('tr:even').addClass('even', function(){
console.log('Hello');
});

Notice how there is a semi colon after the closing braces. This would not normally be needed for a JS function, however this code is still considered to be on one line (as the callback is inside brackets).

Animation

JQuery makes it very easy to animate webpages. You can fade elements in or out:

$('.fade1').fadeIn('slow');

$('#fade2').fadeOut(500);

You can specify three speeds (slow, medium, fast) or a number representing the speed in milliseconds (1000ms = 1 second). You can animate almost any CSS element. This animates the width of the selector from its current width to 250px.

$('foo').animate({width: '250px'});

It's not possible to animate colors. You can use callbacks with animation as well:

$('bar').animate({height: '250px'}, function(){
$('bar').animate({width: '50px'}
});
Loops

Loops really shine in jQuery. Each() is used to iterate over every element of a given type:

$('li').each(function() {
console.log($(this));
});

You can also use an index:

$('li').each(function(i) {
console.log(i + ' - ' + $(this));
});

This would print 0, then 1 and so on.

You can also use each() to iterate over arrays, just like in JS:

var cars = ['Ford', 'Jaguar', 'Lotus'];

$.each(cars, function (i, value){
console.log(value);
});

Note the extra argument called value -- this is the value of the array element.

It's worth noting that each() can sometimes be slower than vanilla JS loops. This is due to the extra processing overhead that jQuery performs. For the majority of the time, this is not an issue. If you are concerned about performance, or are working with large datasets, consider benchmarking your code with jsPerf first.

AJAX

Asynchronous JavaScript and XML or AJAX is really very easy with jQuery. AJAX powers a vast amount of the Internet, and it's something we have covered in part 5 of our jQuery tutorial. It provides a way to partially load a webpage -- no reason to reload the whole page when you only want to update the football score, for example. jQuery has several AJAX methods, the easiest being load():

$('#baz').load('some/url/page.html');

This performs an AJAX call to the page specified (some/url/page.html) and shoves the data into the selector. Simple!

You can perform HTTP GET requests:

$.get('some/url', function(result) {
console.log(result);
});

You can also send data using POST:

$.post('some/other/url', {'make':'Ford', 'model':'Cortina'});

It's very easy to submit form data:

$.post('url', $('form').serialize(), function(result) {
console.log(result);
}

The serialize() function gets all the form data and prepares it for transmission.

Promises

Promises are used for deferred execution. They can be difficult to learn, however jQuery makes it slightly less troublesome. ECMAScript 6 introduces native promises to JS, however, browser support is flaky at best. For now, jQuery promises are much better at cross browser support.

A promise is almost exactly like it sounds. The code will make a promise to return at a later stage when it is complete. Your JavaScript engine will move on to executing some other code. Once the promise resolves (returns), some other piece of code can be run. Promises can be thought of like callbacks. The jQuery documentation explains in greater detail.

Here's an example:

// dfd == deferred
var dfd = $.Deferred();

function doThing() {
$.get('some/slow/url', function() {
dfd.resolve();
});
return dfd.promise();
}

$.when(doThing()).then(function(){
console.log('YAY, it is finished');
});

Notice how the promise is made (dfd.promise()), and it is resolved only when the AJAX call is completed. You could use a variable to keep track of multiple AJAX calls, and only complete another task once all have been made.

Performance Tips

The key to squeezing performance out of your browser is limiting access to the DOM. Many of these tips could apply to JS as well, and you may want to profile your code to see if it is unacceptably slow. In the current age of high performance JavaScript engines, minor bottlenecks in code may often go unnoticed. Despite this, it's still worth trying to write the fastest performing code you can.

Instead of searching the DOM for every action:

$('foo').css('background-color', 'red');
$('foo').css('color', 'green');
$('foo').css('width', '100px');

Store the object in a variable:

$bar = $('foo');

$bar.css('background-color', 'red');
$bar.css('color', 'green');
$bar.css('width', '100px');

Optimize your loops. Given a vanilla for loop:

var cars = ['Mini', 'Ford', 'Jaguar'];

for(int i = 0; i 

While not inherently bad, this loop can be made faster. For every iteration, the loop has to calculate the value of the cars array (cars.length). If you store this in another variable, performance can be gained, especially if you are working with large datasets:

for(int i = 0, j = cars.length; i 

Now the length of the cars array is stored in j. This no longer has to be calculated in every iteration. If you are using each(), you do not need to do this, although properly optimized vanilla JS can outperform jQuery. Where jQuery really shines is through the speed of developing and debugging. If you are not working on big data, jQuery is usually more than fast.

You should now know enough basics to be a jQuery ninja!

Do you use jQuery regularly? Have you stopped using it for any reasons? Let us know your thoughts in the comments below!

Close
Recommended I used to leave my PC on 24/7 until I checked what it was actually costing me Your RAM might be running in single-channel mode — here's how to check in 10 seconds I carry this free Windows tool on a USB drive — it's the fastest way to find what's wasting space on any PC These classic shows have 100+ episodes each — and they're all free on Roku right now Join Our Team Our Audience About Us Press & Events Media Coverage Contact Us Follow Us Advertising Careers Terms Privacy Policies MakeUseOf is part of the Valnet Publishing Group Copyright © 2026 Valnet Inc.

A Basic Guide to JQuery for Javascript Programmers,AI智能索引,全网链接索引,智能导航,网页索引

    If you are a Javascript programmer, this guide to JQuery will help you start coding like a ninja.