Getting started with jQuery

Source: Internet
Author: User
This article mainly introduces the basic knowledge learning guide for jQuery. jQuery is the most popular JavaScript Library at the moment. For more information, see open a webpage. If HTML is not fully loaded, it is not safe to operate the elements on the page, but is it possible to monitor whether HTML is loaded? JQuery provides a $ (document). ready () method. Any code in ready is executed only after HTML is fully loaded.

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

In addition, it also has a shorthand Method

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

$ (Document). ready () does not only support anonymous methods. It is also possible to execute a named method:

function readyFn() {  // code to run when the document is ready}$(document).ready(readyFn);

Select Element

The most basic concept of jQuery is to "select some elements and then do something for them ". JQuery supports most CSS3 selectors. There are also some non-standard selectors. For details, see http://api.jquery.com/category/selectors/. The following describes the usage of some choice tools:

$ ('# Myid'); // This ID must be unique on the page $ ('p. myclass'); // If the element type is specified, the performance will be improved $ ('input [name = first_name] '); // The speed is a little slow, avoid this usage as much as possible $ ('# contents ul. people li '); $ ('a. external: first '); $ ('tr: odd'); $ (' # myForm: input'); // select all input class elements in the Form $ ('P: visible '); $ ('P: gt (2)'); // All divs except the first three divs in the page $ ('P: animate '); // all the divs that are executing the animation

Notes

When using a pseudo selector such as: visible and: hidden, jQuery actually checks whether they are visible on the page, but not the display value in their css. That is to say, when the physical width and height of an element on the page are greater than 0, it is visible. HoweverWith the exception, jQuery willThe display attribute in the element's CSS to determine whether the element is visible.

For details about jQuery implementation, refer to the code below:

jQuery.expr.filters.hidden = function( elem ) {  var width = elem.offsetWidth, height = elem.offsetHeight,    skip = elem.nodeName.toLowerCase() === "tr";  // does the element have 0 height, 0 width,  // and it's not a ?  return width === 0 && height === 0 && !skip ?    // then it must be hidden    true :    // but if it has width and height    // and it's not a     width > 0 && height > 0 && !skip ?      // then it must be visible      false :      // if we get here, the element has width      // and height, but it's also a ,      // so check its display property to      // decide whether it's hidden      jQuery.curCSS(elem, "display") === "none";};jQuery.expr.filters.visible = function( elem ) {  return !jQuery.expr.filters.hidden( elem );};

Whether the selector result set contains elements

After executing a selector, you may take it for granted to determine whether the selector selects an element:

if ($('p.foo')) { ... }

In fact, this write method is not correct, because no matter whether the selector selects an element or not, it will return an object, and the Boolean value of the object must be true, so this method will not work. In fact, there is a length attribute in the returned object of the selector. Through this attribute, you can determine whether there are several elements in the selector. If no element is selected, 0-false is returned, if an element is selected, the actual number of elements is returned-true.

if ($('p.foo').length) { ... }

Cache the selector

Every time you run a selector, jQuery executes a lot of code. If you need to use the same selector multiple times, it is best to cache the selector to avoid repeated execution of the selector.

var $ps = $('p');

Note: The variable name used as the cache variable in this Code starts with $. This dollar sign is only a common character in JavaScript and has no special meaning. It starts with $, it is just a conventional habit, not a mandatory requirement.

Once the selector is cached in the variable, you can call the jQuery method in the variable, which is no different from calling the selector.

In addition, you must note that the selector can only select elements in the current page. If you add elements to the page after executing the selector, the elements added in the next day are not included in the previous selector, unless you add an element to the page and then execute the selector again.
Selector with Filter Function

Sometimes, after executing a selector, not all elements in the result set are what we want, we need to filter the result set again:

$ ('P. foo'). has ('P'); // All

P. foo $('h1 '). not ('. bar '); // The h1 element of the class marked as bar $ ('ul li '). filter ('. current '); // unordered list with class current $ ('ul li '). first (); // The first element in the unordered list $ ('ul li '). eq (5); // The sixth

Select form Element

JQuery provides some pseudo selectors to select form elements, which is very useful.

  • : Button selection button
  • : Checkbox selection box
  • : Checked: select the selected form Element
  • : Disabled: select the disabled form Element
  • : Enabled: select an enabled form element.
  • : Select the form element of type = "file" for file.
  • : Select the form element of type = "image" for image.
  • ...... ......

$ ('# MyForm: input'); // select all input form elements

How to Use Selector

After the selector is executed, you can call the method in the selector. These methods are divided into two types: getter and setter. getter returns the attributes of the first element in the result set. setter can set the attributes of all elements in the result set.
Chain Operation

Most of the methods in the jQuery selector return jQuery objects. Therefore, after calling a method, you can continue to call other methods on this method, as if you were doing the same thing:

$('#content').find('h3').eq(2).html('new text for the third h3!');

For chained operations, it is important to keep the code readable:

$('#content')  .find('h3')  .eq(2)  .html('new text for the third h3!');

If the elements in the selector change in the chain operation, you can use the $. fn. end method to return the original result set:

$ ('# Content'). find ('h3'). eq (2). html ('new text for the third h3! '). End () // returns the initial result set. eq (0). html ('new text for the first h3! ');

Chain Operations are so easy to use that many other JavaScript libraries have now added similar features. However, you must be careful when using chained operations. Too long chained operations may cause difficulties in code modification and debugging. There are no hard rules on the length of a chain operation-as long as you think you can Hold it.

JQuery performs "overload" on some methods. All the method names used when assigning values or values to an element are the same, but the parameter list is different. When the jQuery method is used to assign values to elements, it is called setter, and the value is called getter. Setter assigns values to all elements in the selector. getter only obtains the value of the first element in the selector.

$('h1').html('hello world'); // settervar str = $('h1').html();  // getter

Setter returns a jQuery object. You can continue to call the jQuery method (chained operation) on this object. getter only puts back the value we want. The returned value is not a jQuery object, so you cannot continue the chained operation.
Operate CSS using jQuery

JQuery can easily set or obtain the CSS attributes of elements.

To use CSS attributes in JavaScript, convert them to camel cased. For example, the font-size attribute in CSS corresponds to fontSize in JavaScript, however, jQuery's $.fn.css method has made special processing on this, no matter which write method is used.

For example:

Var strsize1 = require ('h1'0000.css ('fontsize'); // return "19px" var strsize2 = require ('h1'0000.css ('font-size'); // convert ('fontsize ', '100px '); // assign values to a single employee ('h1'0000.css ({'fontsize': '100px', 'color': 'red'}); // assign values to multiple attributes

As shown above, when assigning values to multiple attributes at a time, an object is actually passed in. This object contains key-value pairs that can represent CSS attributes, many setter methods in jQuery have similar usage.
Class Attribute of the jQuery operation Element

As a getter,$.fn.css, it is really easy to use, but it should be avoided as a setter, because it is generally not recommended to include too many style code in JavaScript code. A more reliable method is to separate style rules into classes, and then use JavaScript to apply the classes to elements:

var $h1 = $('h1');$h1.addClass('big');$h1.removeClass('big');$h1.toggleClass('big');if ($h1.hasClass('big')) { ... }

Dimensions

There are many ways to obtain or modify the size or position of an element in jQuery.

$('H1 '). width ('50px '); // set the width of all h1 elements $('h1 '). width (); // obtain the width of the first h1 element $('h1 '). height ('50px '); // sets the height of all h1 elements $('h1 '). height (); // obtain the height of the first h1 element $('h1 '). position (); // return the location information of the first h1 element. The returned value is an object. // the offset of the position relative to its parent element.

Here is a simple example of jQuery's element size and position information.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.