Jquery fundamentals-(part 4) jquery Core

Source: Internet
Author: User
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

 

 

Jquery Core

 

$ VS $ ()

After the above preparations, we can carefully analyze the methods called by jquery objects. For example:

$('h1').remove();

Most jquery methods are called by jquery objects through the method above; these methods are declared as $. A part of the fn namespace, or a "jquery prototype", and is considered a jquery object method.

However, several methods are not used in the selected results. These methods are also part of the jquery namespace and are considered as the core method of jquery.

This is a very confusing question for new scholars. Remember the following:

1. The method called by jquery selection result is put in the namespace of $. fn, and the selection result is automatically received and returned.

2. The methods defined in the $ namespace are generally tool-type methods and do not apply to the selection structure. They do not automatically pass any parameters, and the returned values are usually arrays.

Here are some examples of object methods with the same name as core methods, such as $. each and $. fn. each. In this case, be especially careful when you read the document to find the appropriate method.

Tool Methods

Jquery provides several tool methods in the $ namespace. These methods are very helpful for conventional programming tasks. The following is an example of some tool methods; for more information about jquery tool methods, please visit the http://api.jquery.com/category/utilities.

$. Trim

Remove spaces at the beginning and end.

$.trim('    lots of extra whitespace    ');// returns 'lots of extra whitespace'
$. Each

Traverse arrays and objects

$.each([ 'foo', 'bar', 'baz' ], function(idx, val) {    console.log('element ' + idx + 'is ' + val);});$.each({ foo : 'bar', baz : 'bim' }, function(k, v) {    console.log(k + ' : ' + v);});

Note:

Jqurey has a $. fn. each method, which is used to traverse the elements in the selection result.

$. InArray

Returns the value of the index in the array. If the value is not in the array,-1 is returned.

var myArray = [ 1, 2, 3, 5 ];if ($.inArray(4, myArray) !== -1) {    console.log('found it!');}
$. Extend

Use the following object property to change the attribute of the first object.

var firstObject = { foo : 'bar', a : 'b' };var secondObject = { foo : 'baz' };var newObject = $.extend(firstObject, secondObject);console.log(firstObject.foo); // 'baz'console.log(newObject.foo);   // 'baz'

If you do not want to change any objects passed through $. extend, pass an empty object as the first object.

var firstObject = { foo : 'bar', a : 'b' };var secondObject = { foo : 'baz' };var newObject = $.extend({}, firstObject, secondObject);console.log(firstObject.foo); // 'bar'console.log(newObject.foo);   // 'baz'
$. Proxy

Return a method that can be executed in the specified scope -- that is, set this to the passed function as the second parameter.

var myFunction = function() { console.log(this); };var myObject = { foo : 'bar' };myFunction(); // logs window objectvar myProxyFunction = $.proxy(myFunction, myObject);myProxyFunction(); // logs myObject object

If you have an object that contains methods, you can pass an object and a method name to return a function that will be executed in the object scope.

var myObject = {    myFn : function() {        console.log(this);    }};$('#foo').click(myObject.myFn); // logs DOM element #foo$('#foo').click($.proxy(myObject, 'myFn')); // logs myObject
Type Verification

As mentioned in "javascript basics", jquery provides some basic tools to determine a specific value type.

Example 4.1: verify any value type

var myValue = [1, 2, 3];// Using JavaScript's typeof operator to test for primative typestypeof myValue == 'string'; // falsetypeof myValue == 'number'; // falsetypeof myValue == 'undefined'; // falsetypeof myValue == 'boolean'; // false// Using strict equality operator to check for nullmyValue === null; // false// Using jQuery's methods to check for non-primative typesjQuery.isFunction(myValue); // falsejQuery.isPlainObject(myValue); // falsejQuery.isArray(myValue); // true
Data method

With your further use of jquery, you will find that this often happens. You want to store the data and elements of an element together. In common javascript, you can add an attribute to the DOM element, but you will face some browser memory leaks. Jquery provides a straightforward way to associate data and elements for storage, and it will maintain memory problems for you.

Example 4.2: store and restore data associated with elements

$('#myDiv').data('keyName', { foo : 'bar' });$('#myDiv').data('keyName'); // { foo : 'bar' }

You can store any type of data in an element. When developing complex applications, you can say that it is not important. In most cases, $. fn. data is used to store the information of other elements.

For example, we want to establish a connection between a group of entries and an internal div tag. We can establish a contact every time we operate on this set of items, but the better solution is to establish a contact only once, and then the pointer pointing to the div tag is passed through $. fn. data is stored on this set of entries.

Example 4.3: use $. fn. data to store relationships between elements

$('#myList li').each(function() {    var $li = $(this), $div = $li.find('div.content');    $li.data('contentDiv', $div);});// later, we don't have to find the div again;// we can just read it from the list item's datavar $firstLi = $('#myList li:first');$firstLi.data('contentDiv').html('new content');

In addition to using $. fn. data for a single key-value pair to store data, you can also store data by an object that contains multiple key-value pairs.

Feature and browser Detection

Although jquery eliminates most tips for javascript browsers, you still need to know the browser environment in many cases.

For this purpose, jquery provides the $. support object and the $. brower object that is not supported. For further documentation on these objects, you can access http://api.jquery.com/jQuery.support/ and http://api.jquery.com/jQuery.browser.

$. Support objects are mainly used to determine the features supported by browsers. They are generally considered to be further support for personalized javascript in different browsers.

The $. browser object is a supplement to $. support, but it is estimated that it will be removed from jquery soon. It provides direct browser brand and Version Detection.

Avoid conflicts with other Class Libraries

If you use the $ variable in another javascript class library, it will conflict with the running. To avoid conflicts, You need to convert jquery into a non-conflict mode before jquery loads the page and tries to use jquery in the page.

When jquery enters non-conflict mode, you have the opportunity to set a variable name to replace $.

Example 4.4: Set jquery to non-conflict Mode

<script src="prototype.js"></script><script src="jquery.js"></script><script>var $j = jQuery.noConflict();</script>

You can continue to use the standard $ to wrap your self-executed anonymous functions. When the author does not know whether another Class Library occupies $, this method is a standard mode for control creation.

Example 4.5: $

<script src="prototype.js"></script><script src="jquery.js"></script><script>jQuery.noConflict();(function($) {   // your code here, using the $})(jQuery)</script>

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.