Javascript tool library and JavaScript tool Library

Source: Internet
Author: User
Tags jquery cdn

Javascript tool library and JavaScript tool Library

Javascript library jQuery

Directory:

I,Search tag and event binding and operation tagComparison

II,Conversion between DOM objects and jquery

III,$ (Document). ready ()

Iv. Chain Operations

5. Operation of elements: value and value assignment

Vi. Operation of elements: Move

VII. Tools and methods

 8. Special Effects

 

I,Search tag and event binding and operation tagComparison

1. Search for tagsComparison ***

(1) Native javascript

Document. getElementsByClassName ("classname"); // search for the document tag based on the class. getElementsByTagName ("elementname"); // search for the document tag Based on the tag name. getElementById ("idname"); // search for the tag document by ID name. getElementsByName ("name"); // search for tags Based on the name attribute
Var ele = document. getElementsByClassName ("start") [0]; ele. parentElement; // find the parent node ele. children; // search for all child tags. firstElementChild; // search for the first child Tag Element ele. lastElementChild; // search for the last sub-Tag Element ele. nextElementSibling; // find the next sibling tag ele. previuselementsibling; // search for the last sibling tag

 

(2) jQuery

The selection expression can be a CSS selector: $ (document) // select the entire document object $ ('# myid') // select the webpage element whose ID is myId $ ('div. myclass') // select the div element whose class is myClass $ ('input [name = first] ') // select the input element whose name attribute is equal to "first" or the jQuery-specific expression $ ('a: first ') // select the first a element in the webpage $ ('tr: odd') // select the odd row of the table $ ('# myForm: input') // select the input element $ ('div: visable') in the form ') // select the visible div element $ ('div: gt (2) ') // select all div elements except the first three $ ('div: animated ') // select the currently animated div Element

Where,#,. Corresponds to the id and css markup symbol in css respectively.

If multiple elements are selected, jQuery provides a filter to narrow the result set: * $ ('div '). has ('P'); // select the div element containing the p element * $ ('div '). not ('. myclass'); // select the div element * $ ('div ') of the class that is not equal to the value of myClass '). filter ('. myclass'); // select the div element * $ ('div ') whose class is equal to myClass '). first (); // select 1st div elements * $ ('div '). eq (5); // select 6th div elements. Sometimes, we need to start from the result set and move it to a nearby element. jQuery also provides the moving method on the DOM tree: $ ('div '). next ('P'); // select the first p element after the div element $ ('div '). parent (); // select the parent element of the div element $ ('div '). closest ('form'); // select the form parent element closest to the div $ ('div '). children (); // select all child elements of the div $ ('div '). siblings (); // select the same level element of the div

 

 

 2.Event binding methodComparison

(1) Native javascript

<Body> <div> <button> click </button> </div> <script> ele_button = document. getElementsByTagName ("button") [0]; ele_button.onclick = function () {alert (123)} </script> </body>

 

(2) jQuery

JQuery can bind events to webpage elements. Run corresponding functions based on different events.

// Bind a click event for the button $ ("# button1 "). click (function () {// execute the hide () method $ ("# img1 "). hide ();});

 

3EventComparison ****

 

Original dom Event

Onclick // click the tag ondbclick // double-click the tag onfocus // The element obtains the focus onblur // The element loses the focus onchange // The domain content changes, it is often used when the form Element onkeydown // The keyboard button is pressed onkeypress // a keyboard button is pressed and released. Onkeyup // a keyboard button is released. Onload // a page or image is loaded. Onmousedown // the mouse button is pressed. Onmousemove // move the mouse. Onmouseout // move the mouse away from an element. Onmouseover // move the mouse over an element. Onmouseleave // move the cursor from the element to onselect // The text is selected. Onsubmit // click the OK button.

 

Currently, jQuery mainly supports the following events:

The. blur () form Element loses focus.The value of the. change () form element changes..Click (). Double-click dblclick. focus () form elements get focus. the focusin () sub-element obtains the focus. the focusout () sub-element loses focus. hover () specifies the processing function for both the mouseenter and mouseleave events. keydown () press the keyboard (for a long time, only one event is returned ). keypress () press the keyboard (a long time key will return multiple events ). keyup () loosen the keyboard. load () element loaded. mousedown (): click the mouse. mouseenter () the mouse enters (entering the child element is not triggered ). mouseleave () move the mouse away (leaving the child element is not triggered ). mousemove () move the mouse inside the element. mouseout () move the mouse away (also triggered when the child element is left ). mouseover () the mouse enters (the sub-element is also triggered ). mouseup () loosen the mouse. ready () DOM loading is complete. the size of the resize () browser window is changed. the position of the scroll () scroll bar changes. select () content in the text box selected by the user. submit () User submission form. toggle () runs multiple functions in sequence based on the number of mouse clicks. unload ()

User leaves page
These events are within jQuery, and they are convenient. bind. You can use. bind () to control events more flexibly. For example, you can bind the same function to multiple events:

$ ('Input'). bind ('click change', // bind the click and change event function () {alert ('hello ');});

 

Sometimes, you only want to run the event once. You can use the. one () method.

$ ("P"). one ("click", function () {alert ("Hello"); // only run once, and will not run later });

 

Unbind () is used to unbind events.

$('p').unbind('click'); 

All event processing functions can accept oneEvent object as a parameterFor example, e in the following example:

$("p").click(function(e){ alert(e.type); //"click" });

 

This event object has some useful attributes and methods:

Event. when a pageX event occurs, the cursor is horizontally located at the upper left corner of the page. when a pageY event occurs, the cursor is perpendicular to the event in the upper left corner of the page. type event type (such as click) event. which key event is pressed by which. data binds data to the event object, and then passes in the event processing function event.tar get event to the webpage element event. preventDefault () blocks the default action of an event (for example, clicking a link will automatically open a new page) event. stopPropagation () Stop the event and bubble up the Layer Element

 

In the event processing function, you can use the this keyword to return the DOM elements for the event:

$ ('A '). click (function () {if ($ (this ). attr ('href '). match ('evil ') {// if it is identified as harmful link e. preventDefault (); // block opening $ (this ). addClass ('evil '); // Add harmful class }});

There are two ways to automatically trigger an event. One is to directly use event functions, and the other is to use. trigger () or. triggerHandler ().

$('a').click();$('a').trigger('click');

 

 

 

II,Conversion between DOM objects and jquery

 

1. How to convert a DOM object to a Jquery object:

Var $ document = $ (document) ($ is the alias of jQuery). For a DOM object, you only need to use $ (DOM object) to convert it into a Jquery object.

2. How to convert a Jquery object to a DOM object:

Var domObject = $ ("# thed ")[Index]Or var domObject = $ ("# thed"). get (index)

 

III,$ (Document). ready ()

1. $ (document). ready () What is the function? What is it?

The ready () function is used to execute code when the document enters the ready state. When DOM is fully loaded (HTML is fully parsed when DOM tree construction is complete), jQuery allows us to execute code. The biggest benefit of using $ (document). ready () is that it applies to all browsers, and jQuery helps us solve cross-browser problems.

 

2. What are the differences between the window. onload () event in javascript and the $ (document). ready () function in jQuery?

  Window. onload $ (Document). ready ()
Execution time You must wait until all the content on the webpage is loaded (including images ). All DOM structures in the web page are executed after being drawn. It is possible that the related content of DOM elements has not been fully loaded.
Write count You cannot write multiple codes at the same time. The following Code cannot be correctly executed: window. onload = function ({alert ("test1");} window. onload = function () {alert ("test2");} The result will only output "test2" You can write multiple
Simplified writing None $ (Document). ready (function () {}); can be abbreviated to $ (function (){});

The onload event of window and the ready method in jquery both have the code in the method executed during page loading. The difference between them is: window. onload = function () {} method is used to load html and all external reference files (images, css styles, and js files. Jquery's ready method does not load external reference files.

The answer is as follows:

 

 

Iv. Chain Operations ***

  After you select a webpage element, you can perform some operations on it.
JQuery allows all operations to be connected and written in the form of a chain. For example:

 $('div').find('h3').eq(2).html('Hello');  

 


It is as follows:

1. $ ('div ') // find div element 2 .. find ('h3 ') // select the h3 element 3 .. eq (2) // select 3rd h3 elements 4 .. html ('hello'); // change its content to "Hello ".

 

This is jQuery's most commendable and convenient feature. The principle is that each step of jQuery operations returns a jQuery object, so different operations can be connected together.
JQuery also provides the. end () method, so that the result set can be taken back one step:

1. $ ('div ') 2 .. find ('h3 ') 3 .. eq (2) 4 .. html ('hello') 5 .. end () // return to the step 6 of Selecting All h3 elements .. eq (0) // select the first h3 element 7 .. html ('World'); // change its content to 'World'

 


. End (): Return to the latest "destructive" operation. If no destructive operation is performed before, an empty set is returned. The so-called "destructive" refers to the operation of any change to the matching jQuery element.

 

5. Operation of elements: value and value assignment ***

The most common requirement for webpage elements is to obtain their values or assign values to them.
JQuery uses the same function to complete values (getter) and values (setter ). Whether it is a value or a value is determined by the function parameters.

Parameters ('h1'hangzhou.html (); // No parameter in html (), indicating that the value of 'h1'hangzhou.html ('hello') In h1 is obtained; // in html (), the parameter "Hello" indicates that h1 is assigned a value.

 


Common values and value assignment functions are as follows:

1 .. html () returns or sets the content of the selected element (inner HTML) 2 .. text () to retrieve or set text content 3 .. attr () retrieves or sets the value of an attribute 4 .. width () is used to retrieve or set the width of an element .. height () retrieves or sets the height of an element. 6 .. val () is used to retrieve or set the value of a form element from html.

 

Note that if the result set contains multiple elements, all the elements in the result set are assigned values, only the value of the first element (. with the exception of text (), It extracts the text content of all elements ).

The value assignment of native javascript is like this.

Ele. innerText and ele. innerHTML

This is the value, and the value assignment is

ele.innerText="<a href='#'>click</a>"ele.innerHTML="<a href='#'>click</a>"

Attribute Value operation attribute

We usually useTag. Attribute

Assigning values to attributes is directly used.Tag. Attribute = ""

But in fact, there is an attribute method.

Attribute Value: ele. getAttribute (attribute name)

Attribute assignment: ele. setAttribute (attribute name)

Delete attribute: ele. removeAttribute (attribute name)

 

Vi. Operation of elements: Move

 

. InsertAfter (), move the div element behind the p element: $ ('div '). insertAfter ('P ');

. After (), add the p element to the front of the div element: $ ('P'). after ('div '); there are four pairs

There are a total of four

1 .. insertAfter () and. after (): insert element 2 from the end of an existing element outside the existing element .. insertBefore () and. before (): insert element 3 from the front outside of the existing element .. appendTo () and. append (): inserts an element 4 from the end of an existing element .. prependTo () and. prepend (): inserts an element from the front of an existing element.

 

1. after ():
Description:
Insert a jQuery object (similar to a DOM element array) After all paragraphs ).

 

<B> Hello </B> <p> I wocould like to say: </p> jQuery code: $ ("p "). after ($ ("B"); Result: <p> I wowould like to say: </p> <B> Hello </B>
View Code

 

2. insertAfter ():
Description:
Insert all paragraphs into one element. Same as $ ("# foo"). after ("p ")

 

HTML code: <p> I wowould like to say: </p> <div id = "foo"> Hello </div> jQuery code: $ ("p "). insertAfter ("# foo"); Result: <div id = "foo"> Hello </div> <p> I wowould like to say: </p>
View Code

 

3. before ():
Description:
Insert a jQuery object (similar to a DOM element array) before all paragraphs ).

 

HTML code: <p> I wowould like to say: </p> <B> Hello </B> jQuery code: $ ("p "). before ($ ("B"); Result: <B> Hello </B> <p> I wowould like to say: </p>
View Code

 

 

4. append ():
Description: adds HTML tags to all paragraphs.

HTML code: <p> I wowould like to say: </p> jQuery code: $ ("p "). append ("<B> Hello </B>"); Result: <p> I wowould like to say: <B> Hello </B> </p>
View Code

 

5. appendTo ()
Description: adds a new section to the div and adds a class.

 

HTML code: <div> </div> jQuery code: $ ("<p/> "). appendTo ("div "). addClass ("test "). end (). addClass ("test2"); Result: <div> <p class = "test test2"> </p> </div> <p class = "test"> </p> </div>
View Code

 

6. prepend ()
Description: A jQuery object (similar to a DOM element array) is prefixed to all paragraphs ).

 

HTML code: <p> I wowould like to say: </p> <B> Hello </B> jQuery code: $ ("p "). result: <p> <B> Hello </B> I wowould like to say: </p>
View Code

 

7. prependTo ()
Description: Adds all paragraphs to the element with the ID value foo.

 

HTML code: <p> I wowould like to say: </p> <div id = "foo"> </div> jQuery code: $ ("p "). result: <div id = "foo"> <p> I wowould like to say: </p> </div>
View Code

 

 

VII. Tool Methods ****

In addition to operations on selected elements, jQuery also provides some tool methods (utility) that can be directly used without selecting elements.
Common tool methods include:

$. Trim () removes spaces at both ends of the string. $. Each () traverses an array or object. $. InArray () returns the index position of a value in the array. If the value is not in the array,-1 is returned. $. Grep () returns elements that conform to a certain standard in the array. $. Extend () combines multiple objects into the first object. $. MakeArray () converts an object to an array. $. Type () determines the object category (function object, date object, array object, regular object, and so on ). $. IsArray () determines whether a parameter is an array. $. IsEmptyObject () determines whether an object is null (excluding any attributes ). $. IsFunction () determines whether a parameter is a function. $. IsPlainObject () determines whether a parameter is an Object created with "{}" or "new Object. $. Support () determines whether the browser supports a certain feature.

 

 

8. Special Effects

JQuery allows objects to present certain special effects.

$('H1 '). show (); // displays an h1 title
Common special effects are as follows:

. FadeIn () fades in. fadeOut () fade out. fadeTo () adjusts transparency. hide () hides elements. show () display element. slideDown () to expand down. slideUp () is rolled up. slideToggle () expands or rolls up an element in sequence. toggle () displays or hides an element in sequence.

 

Except for. show () and. hide (), the default execution time of all other effects is 400 ms (ms), but you can change this setting.

* $('H1 '). fadeIn (300); // fade in within 300 milliseconds
* $('H1 '). fadeOut ('low'); // fade out slowly
After the special effect ends, you can specify to execute a function.

$('p').fadeOut(300, function(){$(this).remove(); }); 

You can use. animate () to customize more complex effects.

$ ('Div '). animate ({left: "+ = 50", // shift right continuously opacity: 0.25 // specify transparency}, 300, // duration function () {alert ('done! ');} // Callback function );

 

. Stop () and. delay () are used to stop or delay the execution of special effects.
$. Fx. off if set to true, disable all webpage effects.

Several common filter selectors:

Filter (): filter the set of elements that match the specified expression. This method is used to narrow the matching range. Multiple Expressions separated by commas
Description: The sub-element containing ol is retained.

HTML code:

<p><ol><li>Hello</li></ol></p><p>How are you?</p>

 

JQuery code:

$("p").filter(function(index) { return $("ol", this).length == 0;});

Result:

<p>How are you?</p>

 

Silce (): select a matched subset.

Description: select the first p element.

HTML code:

<p>Hello</p><p>cruel</p><p>World</p>

 

JQuery code:

$("p").slice(0, 1).wrapInner("<b></b>");

 

Result:

<p><b>Hello</b></p> 

 

 

 

 

How to Use JQuery CDN? We recommend that you use the official CDN node. The Code is as follows:

<script src="//code.jquery.com/jquery-1.11.0.min.js"> </script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"> </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.