Basic jquery tutorial (jQuery Fundamentals) -- (part 3) Basic jquery

Source: Internet
Author: User
Document directory
  • $ (Document). ready ()
  • Selecting Elements)
  • Select Selector
  • Is there any element in my selector?
  • Save selection result
  • Extract and filter selection results
  • Select Form Element
  • Use of selection results
  • CSS, style, and size
  • Attribute (Attributes)
  • Link search)
  • Manipulating Elements)
  • Move, copy, and remove elements
  • Create a new element
  • Operation attribute
  • Exercise
Basic Jquery tutorial

Author: Rebecca Murphey

Original link address http://jqfundamentals.com/

With contributions by James Padolsey, Paul Irish, and others. See the GitHub repository for a complete history of contributions.

Copyright 2011

 

Basic jquery tutorial (jQuery Fundamentals)-Overview

Jquery Fundamentals-javascript Basics

Jquery Fundamentals-jQuery Basics

Jquery Fundamentals-jQuery Core

Jquery Fundamentals-Events

Basic jquery tutorial (jQuery Fundamentals)-Effect

Jquery Fundamentals-Ajax

Basic jquery tutorial (jQuery Fundamentals)-plugin

Jquery Fundamentals-best performance practices

Jquery Fundamentals-Code Organization

Jquery Fundamentals-custom events

 

 

Jquery Basics

 

 

$ (Document). ready ()

On the page, you can operate the page content only after the document object is loaded. Jquery provides you with a way to determine that this state is ready: at $ (document ). the Code contained in the brackets of ready () is loaded on the page and executed after javascript code is executed.

Example 3.1: $ (document). ready () code block

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

You may see some shorthand for $ (document). ready (). However, I do not recommend shorthand for jquery programmers.

Example 3.2: $ (document). ready ()

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

The most basic concept of jquery is to "select and operate on some elements ". Jquery provides most selectors in css3, and colleagues also provide some non-standard selectors. To get a complete introduction to selector, you can access the http://api.jquery.com/category/selectors.

Below are some commonly used selection techniques.

Example 3.4: select an element by ID

$('#myId'); // note IDs must be unique per page

Example 3.5: select an element using the class name

$('div.myClass'); // performance improves if you specify element type

Example 3.6: select an element using properties

$('input[name=first_name]'); // beware, this can be very slow

Example 3.7: Use a composite css selector to select an element

$('#contents ul.people li');

Example 3.8: Use a pseudo selector to select an element

$('a.external:first');
$('tr:odd');
$('#myForm :input');   // select all input-like elements in a form
$('div:visible');
$('div:gt(2)');        // all except the first three divs
$('div:animated');     // all currently animated divs

 

Note:

When you useVisibleAnd: HiddenWhen the pseudo selector is used,JqueryChecks the actual visible attribute of the element, instead of itsCssAttribute or display attribute--That is to say, it will check whether the physical attributes of this element on the page are greater0.However, this mechanism does not check<Tr>Element; at this time,JqueryCheck itsCSSDisplay the property, and think that when the propertyDisplayThe property isNoneIs hidden. For allDOMThe elements on, even ifCSSThey can be affected and rendered. (Later in this chapter, we will talk about how to add elementsDOM).

For reference, the following provides someJqueryTo determine whether the elements are visible or hidden.

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 <tr>?
    return width === 0 && height === 0 && !skip ?
        // then it must be hidden
        true :
        // but if it has width and height
        // and it's not a <tr>
        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 <tr>,
            // 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 );
};
Select Selector

Selecting the proper selector is a good way to improve the performance of your javascript code. Specific features-for example, when you use the class name to select a tag containing the div tag-are a good choice. In general, you should give jquery some hints about where it will find the elements you want to find. On the other hand, too specific features will become harmful. If the image#myTable th.specialThis selector can find the elements you want.Image#myTable thead tr th.special

This selector is too specific.

Jquery provides many attribute-based selectors that allow you to use regular expressions to create selectors based on various attributes.

// find all <a>s whose rel attribute
// ends with "thinger"
$("a[rel$='thinger']");

However, this type of selector is still very useful in a few cases, but their performance is not flattering-I once again wrote a property-based selector, it locks the page for several seconds. If possible, use ID, class name, and label name to create a selector.

Want to know more? Paul Irish has a great presentation about improving performance in JavaScript, here is an example of downgrading selector performance.

Is there any element in my selector?

Once you create a selector, you usually want to know whether you have obtained the element through this selector. You may use the following method to do something:

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

This will not be useful! After you select $ (), an object is always returned, and the value calculated by the object is always true. Even if your selector does not get any elements, the statement blocks under if will always be executed.

You need to pass the length attribute of the test result, which will tell you how many elements have been selected. If the result is 0, the length attribute calculated when used as a boolean variable is false.

Example 3.9: Check whether the selected result contains elements.

if ($('div.foo').length) { ... }
Save selection result

Every time you perform the selection operation, you will execute a lot of code. jquery will not help you cache the selection result. After you execute an option, you will often use it and get the result. You can save it to a variable instead of executing it repeatedly. This will improve the performance.

Example 3.10: store the selected result in a variable

var $divs = $('div');

Note:

In the example of 3.10, the variable name starts with $. Unlike other languages, $ has no special meaning in javascript-it is just a character. Here we have a variable that declares a jquery object. This is a convention, but it is not mandatory.

After you store the selected result, you can use jquery to call the stored variable, which is no different from the result returned by calling the original selector.

Note:

When you execute the selector, it only gets the elements of the current page. If you add another element on the page, you have to re-execute the selection and then store it. That is to say, when the DOM changes, the stored selection results will not be magically updated.

Extract and filter selection results

Sometimes you get such a selection result, which not only contains what you need; in this case, you will want to extract your selection result. Jquery provides some methods to streamline the selection results.

Example 3.11: extract the selection result

$('div.foo').has('p');          // div.foo elements that contain <p>'s
$('h1').not('.bar');            // h1 elements that don't have a class of bar
$('ul li').filter('.current');  // unordered list items with class of current
$('ul li').first();             // just the first unordered list item
$('ul li').eq(5);     
Select Form Element

Jquery provides some pseudo selectors to help you select elements in Forms. They are especially useful because it is difficult to distinguish them based on the state and type of elements through standard css selectors.

: Button

Select the <button> element and the element with the property type = "button"

: Checkbox

Select an element with the property type = "checkbox"

: Checked

Select selected input

: Disabled

Select unavailable Elements

: Enabled

Select available elements

: File

Select an element with the property type = file

: Image

Select an element with type = "image"

: Input

Select<input>,<textarea>,<select>Element

: Password

Select an element with the property type = "password"

: Radio

Select an element with the property type = "radio"

: Reset

Select an element with the property type = "reset"

: Selected

Select any selected Element

: Submit

Select an element with the property type = "submit"

: Text

Select input with attribute type = "text"

Example 3.12: use of form-related pseudo Selector

$('#myForm :input'); // get all elements that accept input
 
Use of selection results

Once you get the selection result, you can select the result to call the method above. Methods are generally divided into two types: getters and setters. Getters returns an attribute of the first selected element. setters adds an attribute to all selected elements.

Chain Programming

If you call a method on a selection result and the method returns a jquery object type, you can continue to call the jquery Method on this jquery object without the need for concluding remarks.

Example 3.13:

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

If the statement chain you write contains several steps, you will find that your code will become readable if you divide them into multiple lines of books.

Example 3.14: format the chained code

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

If you want to change the selection result in the middle of the statement chain, jquery provides the $. fn. end method, and you can return the starting selection result.

Example 3.15: use $. fn. end to reply to the original selection result

$('#content')
    .find('h3')
    .eq(2)
        .html('new text for the third h3!')
    .end() // restores the selection to all h3's in #content
    .eq(0)
        .html('new text for the first h3!');

 

Note:

Chain statements are very powerful. Since jquery became popular, many js libraries provide this feature. However, you must be very careful when using it. A large number of chain statements are extremely difficult to debug code. There is no forcible rule on how long a statement chain should be -- as long as it is easy to understand.

Getters and setters

Jquery "reloads" these two methods, so adding one and getting one is the same. When a method is used to add a value, it is called a setter. When a method is used to obtain a value, it is called getter. Setters acts on all selected elements. getters is only used to select the first element in the result.

Example 3.16: Using .fn.html as the setter

$('h1').html('hello world');

Example 3.17: Using .fn.html as the getter

$('h1').html();

Setters returns a jquery object, allowing you to continue calling the jquery method in the selection result; getters returns a requested object, that is, you cannot continue calling the jquery method in the selection result.

CSS, style, and size

Jquery contains a very convenient way to get and set element css attributes.

Note:

Css attributes are generally called by camels in javascript. For example, in javascript, the font-size attribute of css is usually named as fontSize. This does not mean that other naming methods are not allowed. This is only a convention.

Example 3.18: Obtain css attributes

$('h1').css('fontSize'); // returns a string such as "19px"
$('h1').css('font-size'); // also works

Example 3.19: Set css attributes

$('h1').css('fontSize', '100px'); // setting an individual property
$('h1').css({ 'fontSize' : '100px', 'color' : 'red' }); // setting multiple properties

Note: In the second sentence in the above example, the parameter format we use is an object-it contains multiple attributes. This is a common method used to pass multiple parameters. Many jquery setter Methods transmit multiple values at a time by accepting objects.

Use css classes to set styles

The getter.fn.css method is very valuable. However, you should avoid applying this method to a finished code as a setter, because you should not describe this information in your javascript code. Instead, you should write css rules in classes to describe different visual effects, and then use jquery to easily change the desired effects.
Example 3.20: Use of classes

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

Classes can also be used to store the status information of an element. For example, the declared element is deleted.

Dimensions

Jquery provides many methods to obtain and modify the size and position information of an element.

The code in example 3.21 is a typical application of the dimensional transformation in jquery; to learn more about the jquery dimensional method, visit: http://api.jquery.com/category/dimensions.

Example 3.21: Basic Dimension Method

$('h1').width('50px');   // sets the width of all H1 elements
$('h1').width();         // gets the width of the first H1
$('h1').height('50px');  // sets the height of all H1 elements
$('h1').height();        // gets the height of the first H1
$('h1').position();      // returns an object containing position
                         // information for the first H1 relative to
                         // its "offset (positioned) parent"
Attribute (Attributes)

For an application, the attribute of an element contains a lot of useful information, so it is very important to obtain and set them.

$. Fn. attr can be either getter or setter. $. Fn. attr, as a setter, can accept both a key-Value Pair and an object that contains multiple key-value pairs.

Example 3.22: Set attributes

$('a').attr('href', 'allMyHrefsAreTheSameNow.html');
$('a').attr({
    'title' : 'all titles are the same too!',
    'href' : 'somethingNew.html'
});

This time we divide the object into multiple lines of writing. spaces are meaningless in javascript, so you can apply them freely to make your code look clearer! You can use some tools to remove spaces for finished code (to be released.

Example 3.23: Get attributes

$('a').attr('href');  // returns the href for the first a element in the document
Link search)

(Do not know if the translation is correct ......)

When you get a jquery selection result, you can find other elements based on the selection structure.

For more details about the Association lookup method, you can see the http://api.jquery.com/category/traversing/ here.

Note:

In your code, you must be cautious about applying too long association searches-complex association searches need to keep the structure of your page unchanged, but sometimes it is hard to ensure that you only have one developer. You can perform Association search in one or two steps, but also avoid cross-origin Container Association.

 

Example 3.24: Move the DOM element using the association lookup Method

$('h1').next('p');
$('div:visible').parent();
$('input[name=first_name]').closest('form');
$('#myList').children();
$('li.selected').siblings();

You can use $. fn. each to traverse a selection result. This method traverses all the elements in the selection result and executes a function for each element. This function accepts the subscript of the current element and the DOM element as the parameter. In the function, DOM elements can be replaced by the this keyword by default.

Example 3.25:

$('#myList li').each(function(idx, el) {
    console.log(
        'Element ' + idx +
        'has the following html: ' +
        $(el).html()
    );
});
Manipulating Elements)

 

Once you execute a selection statement, it's a good start. You can change, move, remove, and copy elements. You can also create new elements using simple syntax.

For more information about juquery operations, visit: http://api.jquery.com/category/manipulation.

Obtain and set Element Information

You can change an existing element in many ways. In your daily coding, the most common thing you do is to change the internal html code or attributes of an element. Jquery provides many simple, cross-browser methods for these operations. You can obtain the element information by having the get and set functions at the same time. We will provide several examples in this section.

Note:

Modifying the information about an element is trivial, but remember that modification affects all the elements in the selection result. Therefore, if you only want to change an element, make sure that before you call setter, there is only one element in your selection result.

Note:

When you use methods as getter, they usually only act on the first element in the selection result and do not return jquery objects. Therefore, you cannot use chained statements. One exception is $. fn. text. As mentioned in the following example, it obtains the text information of all elements in the selection result.

Developer.fn.html

Get or set html content

$. Fn. text

Get or set the text content after html Stripping

$. Fn. attr

Obtains or sets the provided attributes.

$. Fn. width

Obtain or set the pixel width of the first element in the selection result to an integer.

$. Fn. height

Obtain or set the pixel height of the first element in the selection result to an integer.

$. Fn. position

Gets an object with the location information of the first element in the selection result, relative to its location of the identified ancestor tag. (Getter only)

$. Fn. val

Obtains or sets the value of an element.

Move, copy, and remove elements

There are many ways to move elements in the DOM; In general there are two ways:

1. Place the selected object based on another object

2. Place another object based on the selected object

For example, jquery provides $. fn. insertAfter and $. fn. after. $. Fn. the insertAfter method places the selected element behind the element used as the parameter; $. fn. the after method places the element as a parameter after the selected element. Several other methods follow this pattern. $. Fn. insertBefore and $. fn. before; $. fn. appendTo and $. fn. append; and $. fn. prependTo and $. fn. prepend.

These methods fully depend on the elements you select and whether you need to reference the elements added to the page. If you need to store this reference, you should select the first method -- place the selected element based on another element -- it returns the element you want to place. In this case, you use $. fn. insertAfter,$.fn.insertBefore,$.fn.appendTo, And$.fn.prependTo

Example 3.27: move elements in different ways

// make the first list item the last list item
var $li = $('#myList li:first').appendTo('#myList');
// another approach to the same problem
$('#myList').append($('#myList li:first'));
// note that there's no way to access the
// list item that we moved, as this returns
// the list itself
Copy Element

When you use the $. fn. appendTo method, you move the element. Sometimes you want to not only move, but also copy the element. This is, you need the $. fn. clone Method

Example 3.28: copy an element

// copy the first list item to the end of the list
$('#myList li:first').clone().appendTo('#myList');

Note:

If you want to copy associated data or events, make sure to pass a true parameter to $. fn. clone.

Remove Element

There are two ways to remove elements on the page: $. fn. remove and $. fn. detach. You can use $. fn. remove; this method returns the removed elements. If you add them to the page again, the previously associated data and events will disappear.

If you want to maintain the associated data and events, you can use $. fn. detach instead. Like $. fn. remove, it also returns the selected element, but maintains the associated data and events at the same time, so you can restore the element after a period of time.

Note:

$. Fn. detach is very useful when you have a large number of operations on an element. In this case, detach the element from the page and operate it in the Code. After you finish, restore it to the page. This avoids expensive DOM details when you maintain element data and events.

If you want to keep the element on the page and just remove its content, you can use the $. fn. empty method to release the internal html of the element.

Create a new element

Jquery provides a variety of methods to create new elements-just like using the $ () method to select elements.

Example 3.29: Create a new element

$('<p>This is a new paragraph</p>');
$('<li class="new">new list item</li>');

Example 3.29: Create a new element using an attribute object

$('<a/>', {
    html : 'This is a <strong>new</strong> link',
    'class' : 'new',
    href : 'foo.html'
});

Note: In the above example, we added the second parameter, and the class of the attribute name was included,
Href and html do not. When the attribute name is not a reserved word, it must be included.

When we create a new element, it is not immediately added to the page. Here are several methods to add a page to the page after the page is created.

Example 3.31: Add a new element to the page

var $myNewElement = $('<p>New element</p>');
$myNewElement.appendTo('#content');
$myNewElement.insertAfter('ul:last'); // this will remove the p from #content!
$('ul').last().after($myNewElement.clone());  // clone the p so now we have 2

Strictly speaking, you do not need to store new elements in variables-you can directly add elements to the page through $. But most of the time, you need a reference to add new elements so that you don't have to select them again.

You can add a new element to the page while creating it, but you will lose the reference of the newly added object.

Example 3.32:

$('ul').append('<li>list item</li>');
 
Note:
The syntax for adding new elements to a page is so simple that people forget that repeated addition is a huge waste of performance. If you add many elements to the same container
The html code is connected to a string and then added to the container, instead
Add an element. You can use arrays to collect all element fragments, and then use join to convert them into one
Strings.
 
 
var myItems = [], $myList = $('#myList');
for (var i=0; i<100; i++) {
    myItems.push('<li>item ' + i + '</li>');
}
$myList.append(myItems.join(''));
 
Operation attribute

Jquery contains a large number of attribute operations. The basic operation is simple, but the $. fn. attr method also provides many complex operations, which can be used to set a simple value or set a value through the return value of the function. When using the function syntax, the function accepts two parameters: the 0-base index of the element of the modified attribute, and the value of the current attribute.

Example 3.33:

$('#myDiv a:first').attr('href', 'newDestination.html');
 
Example 3.34:
$('#myDiv a:first').attr({
    href : 'newDestination.html',
    rel : 'super-special'
});

Example 3.35:

$('#myDiv a:first').attr({
    rel : 'super-special',
    href : function(idx, href) {
        return '/new/' + href;
    }
});
$('#myDiv a:first').attr('href', function(idx, href) {
    return '/new/' + href;
});
 
Exercise
(Omitted)
 
 

 

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.