jquery common methods and use sample Rollup _jquery

Source: Internet
Author: User
Tags wrapper javascript array

MouseOver ()/mouserout ()

Triggers the Mouseover/mouseout event when the mouse enters/leaves an element or its descendant elements.
MouseOver events are most often used in conjunction with the Mouseout event.

Due to the bubbling mechanism, the Mouseover/mouserout event is often inadvertently triggered when it is not needed, causing some scripting problems.

MouseEnter ()/mouseleave ()

Mouseenter/mouseleave is triggered only when the mouse enters the selected element and is not triggered when the mouse crosses any child elements. It does not care whether the target element has child elements.

Focusin () and Focusout ()

. Focusin (): This event is triggered when an element or its child element gets the focus
. Focusout (): This event is triggered when an element or its child element loses focus

Unlike the focus () method, the Focusin () method is also triggered when any child element obtains the focal point.

Copy Code code as follows:

<body>
<p><input type= "text" > <span>focusin fire</span></p>
<p><input type= "Password" > <span>focusin fire</span></p>
<script>
$ ("P"). Focusin (function () {
$ (this). FIND ("span"). CSS ("display", "inline"). fadeout (1000);
});
</script>
</body>

EQ () and get ()

. Get (): Gets a corresponding DOM element from the jquery object.
. EQ (): Constructs a new jquery object from one element of a collection

The EQ returns a JQuery object, and the Get returns a DOM object. As an example:

$ ("Li"). Get (0). CSS ("Color", "red"); Error
$ ("li"). EQ (0). CSS ("Color", "red"); That's right
So, what is a DOM object and what is a jquery object?

The DOM object is the object that is obtained with JS, and the Juqery object is the object that is obtained using the jquery class library selector.

such as: var $obj = $ ("div");//jquery Object

The Get method essentially converts the JQuery object into a DOM object, but the CSS is part of the jquery constructor, and the DOM does not exist, and if you need to use the JQuery method, we have to write it this way:

Copy Code code as follows:

var li = $ ("li"). Get (0);
$ (LI). css ("Color", "black");

Filter ()

Filter () Method: Filters out the collection of elements that match the specified expression.
This method is used to narrow the range of matches. Separate multiple expressions with commas.

Filter (expression): (String | function) If the argument is a string, develop a jquery selector that deletes all elements that do not match the selector from the wrapper set, leaving the element that matches the selector, and then determines the filter criteria if the parameter is a function. This function is called once for each element in the wrapper set, and any element that returns false from the function call will be removed from the wrapper set.

The following code means preserving the first and elements with a select class

HTML Code:

Copy Code code as follows:

<p>hello</p><p>hello again</p><p class= "selected" >and again</p>

JQuery Code:

Copy Code code as follows:

$ ("P"). Filter (". selected,: a")

Results:

Copy Code code as follows:

<p>hello</p>, <p class= "selected" >and again</p>

Look at an example of a function that is used as a collection of test elements. It accepts a parameter index, which is the index of the element in the jquery collection. In function, this refers to the current DOM element.

HTML Code:

Copy Code code as follows:

<p><ol><li>hello</li></ol></p><p>how are you?</p>

JQuery Code:

Copy Code code as follows:

$ ("P"). Filter (function (index) {
return $ (' ol ', this). length = = 0;
});

Results:

Copy Code code as follows:

<p>how are you?</p>

. Bind (),. Live () and. Delegate () methods

. Bind (): The most basic way to bind an event-handling function is to use the. bind () method. Like the Live () method, it accepts two parameters:

. Bind (Event type, event handler)
Two methods for binding event-handling functions:

Copy Code code as follows:

$ (document). Ready (function () {
$ ('. Mydiv '). Bind (' click ', test);

function Test () {
Alert ("Hello world!");
}
});

The event handler function can also use anonymous functions, as follows:

Copy Code code as follows:

$ (document). Ready (function () {
$ ("#mydiv"). Bind ("click", Function () {
Alert ("Hello world!");
})
});

Live (): The only difference between the live method and the Bind method is that. Live () is used not only for elements that are currently present in the DOM, but also for possible (dynamically generated) elements in the future

Copy Code code as follows:

$ (document). Ready (function () {
$ ('. Box '). Live (' click ', function () {
$ (this). Clone (). Appendto ('. container ');
});
});

<div class= "Container" >
<div class= "box" ></div>
</div>

The disadvantage of using the live method to bind an event is that it cannot use chained calls, and is there a way to bind events like live methods and support chained calls? The answer is the following delegate method.

Delegate () Method: Adds one or more event handlers for the specified element, which belongs to the child element of the selected element.
and specify which functions to run when these events occur. Starting with jquery 1.7,. Delegate () has been replaced by the. On () method.
Grammar:

$ (selector). Delegate (Childselector,event type,function)
Parameter description:

Childselector required. Specify one or more child elements to attach an event handler to.

Event required. Specify one or more events that are attached to an element. Multiple event values are separated by a space. Must be a valid event.

function Required. Specify the function to run when an event occurs.

Copy Code code as follows:

$ (document). Ready (function () {
$ ('. Container '). Delegate ('. Box ', ' click ', function () {
$ (this). Clone (). Appendto ('. container ');
});
});

Delegate () will be used in the following two scenarios:

1, if you have a parent element, you need to add an event to its child elements, then you can use Delegate (), the code is as follows:

Copy Code code as follows:

$ ("ul"). Delegate ("Li", "click", Function () {

$ (this). Hide ();

});

2, when the element is not available in the current page, you can use Delegate ()

End () method

End () method: called within the jquery command chain to return to the previous wrapper set.
Each filtering method is pressed into the stack. When we need to go back to the previous state, we can use end () to do the stack operation to return to the previous state in the stack.

The end () method ends the most recent filter operation in the current chain and restores the set of matching elements to the previous state.

Copy Code code as follows:

<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<title></title>
<script src= "Http://libs.baidu.com/jquery/1.9.0/jquery.js" ></script>
<body>
<ul class= "One" >
<li class= "two" >item 1</li>
<li>item 2</li>
<li class= "three" >item 3</li>
</ul>

<script type= "Text/javascript" >
$ (' Ul.one '). Find (". Two"). CSS ("Color", "red"). Find ('. three '). CSS ("Background", "blue");
</script>

In the code example above, we will only see that the font color of item 1 changes, and the background color does not change. This is because
The state before the second find () method returns an object with a two class value of the red font, so the second discovery () only looks for the. Two in <ul class= "One" >, using the End () method to modify the code for the chained operation as follows:

Copy Code code as follows:

<script type= "Text/javascript" >
$ (' Ul.one '). Find (". Two"). CSS ("Color", "red"). End (). Find ('. three '). CSS ("Background", "blue");
</script>

The end () method is here to return the state before the call to find (), which is $ (' Ul.one ')

Toggleclass ()

' Toggleclass () method: ' If the specified class name does not exist in the element, the specified class name is added; If the element already has the specified
Class name, the specified class name is removed from the element.
CSS (Name,value) method: Sets the specified value to a specific CSS style property for each matched element

Wrap () and Wrapinner ()

' Wrap () and Wrapinner (): ' The former wraps all the matching elements in a structured notation of other elements;
The latter wraps the child content of each matching element (including the text node) in an HTML structure.
Look at the following example of a wrap ():
Use the contents of the original Div as the class of the new div and wrap each element together

HTML Code:

Copy Code code as follows:

<div class= "Container" >
<div class= "inner" >Hello</div>
<div class= "inner" >Goodbye</div>
</div>

JQuery Code:

Copy Code code as follows:

$ ('. Inner '). Wrap (function () {
Return ' <div class= ' + $ (this). Text () + '/> ';
});

Results:

Copy Code code as follows:

<div class= "Container" >
<div class= "Hello" >
<div class= "inner" >Hello</div>
</div>
<div class= "Goodbye" >
<div class= "inner" >Goodbye</div>
</div>
</div>

Then look at the following example of a Wrapinner ():

Use the contents of the original Div as the class of the new div and wrap each element together

HTML Code:

Copy Code code as follows:

<div class= "Container" >
<div class= "inner" >Hello</div>
<div class= "inner" >Goodbye</div>
</div>

JQuery Code:

Copy Code code as follows:

$ ('. Inner '). Wrapinner (function () {
Return ' <div class= ' + $ (this). Text () + '/> ';
});

Results:

Copy Code code as follows:

<div class= "Container" >
<div class= "inner" >
<div class= "Hello" >Hello</div>
</div>
<div class= "inner" >
<div class= "Goodbye" >Goodbye</div>
</div>
</div>

Detach, empty and remove methods

. Detach ([selector]): Removes all matching elements from the DOM. When you need to move an element and soon insert the element into the DOM, you need to use the detach method.

. Empty (): This method removes not only the child elements (and other descendant elements), but also the text in the element. Because, according to the instructions, any text string in an element is considered to be a child of that element.

. remove ([selector]): Removes elements from the DOM while removing events and jQuery data on elements

Examples of empty ():

Copy Code code as follows:

<ul class= "One" >
<li class= "two" >item 1</li>
<li>item 2</li>
<li class= "three" >item 3</li>
</ul>

<script type= "Text/javascript" >
$ (". Two"). empty ();//item 1 text node removed, Li's dot is still there, proving that Li has not been removed
</script>

Look at one of the following remove () Examples:

Description: Remove all paragraphs from the DOM

HTML Code:

Copy Code code as follows:

<p>Hello</p> how are <p>you?</p>

JQuery Code:

Copy Code code as follows:

$ ("P"). Remove ();

Results:

How are
Val () method

Val (): Gets the current value of the matching element.
Description: Gets the value in the text box

JQuery Code:

Copy Code code as follows:

$ ("input"). Val ();

JQuery Code:

Copy Code code as follows:

$ ("input"). val ("Hello world!");

each () and map ()

each () and map () method: Each returns the original array, and no new array is created. And the map method returns a
The new array. If you use a map if it is not necessary, you can create a waste of memory.
Each method:

Defines an empty array, adds an ID value to the array by each method, and finally converts the array to a string, alert this value;

Copy Code code as follows:

$ (function () {
var arr = [];
$ (": CheckBox"). each (function (index) {
Arr.push (this.id);
});
var str = arr.join (",");
alert (str);
})

Map method:

Performs a return this.id for each: CheckBox and returns these values automatically to the jquery object, then converts it to a native JavaScript array using the Get method, and then converts it to a string with the Join method, with the last alert value;

Copy Code code as follows:

$ (function () {
var str = $ (": CheckBox"). Map (function () {
return this.id;
}). Get (). Join ();
alert (str);
})

It is convenient to use the map method when the value of an array is needed.

For more detailed discussion, please click on my other article: detailed jquery built-in function map () and each () use

$.each ()

jquery $ (selector). The each () function iterates through the selected child elements, while jquery's $.each () function iterates through any set, including objects and arrays, which receives the collection to traverse and a callback function, Each time the callback function passes the subscript of an array and the value of the array corresponding to the subscript.

$.each (Array,callback);

$.each (Object,callback);
Array instances

Copy Code code as follows:

$.each (["One", "two", "three"], function (i, L) {
Alert ("Index #" + i + ":" + L);
});

Callback (index, index value)
DEMO:

Index 0:one
Index 1:two;
Index 2:three
Object instance

$.each ({name: "John", Lang: "JS"}, function (k, v) {
Alert ("Key:" + K + ", Value:" + V);
});
Callback (key, value)
Demo:

Key:name, VALUE:TRIGKIT4
Key:ages, value:21
. Trigger ()

Description: Executes all handlers and behaviors based on the given event type that is bound to the matching element.

When the corresponding event occurs, any event handlers that are bound by. On () or a shortcut method are triggered. However, they can be manually triggered using the. Trigger () method

Copy Code code as follows:

<script type= "Text/javascript" >
$ (document). Ready (function () {
$ ("input"). Select (function () {
$ ("input"). After ("Text is selected!") ");
})

$ ("button"). Click (function () {
$ ("input"). Trigger ("select");
})
})
</script>

. attr () and. Prop ()

. attr (): Gets the value of the property of the first element in the matching element collection or sets one or more properties for each matching element.

. Prop (): Ibid.
Before JQuery 1.6, the. attr () method returns the value of the property when it takes a value of some attribute, which results in inconsistency. Starting with JQuery 1.6, the. Prop () method returns the value of the property, whereas the. attr () method returns the value of attributes.

For example, SelectedIndex, TagName, NodeName, NodeType, Ownerdocument, defaultchecked, and defaultselected should use the. Prop () method to fetch or assign values.

They have no corresponding attributes (attributes), only attributes.

. After () and. InsertAfter ()

1.after ()

Describe:
Inserts a jquery object (similar to an array of DOM elements) after all the paragraphs.

HTML Code:

Copy Code code as follows:

<b>hello</b><p>i would like to say: </p>

JQuery Code:

Copy Code code as follows:

$ ("P"). After ($ ("B"));

Results:

Copy Code code as follows:

<p>i would like to say: </p><b>Hello</b>

2.insertAfter ()

Describe:
Inserts all the paragraphs behind an element. and $ ("#foo"). After ("P") the same

HTML Code:

Copy Code code as follows:

<p>i would like to say: </p><div id= "foo" >Hello</div>

JQuery Code:

Copy Code code as follows:

$ ("P"). InsertAfter ("#foo");

Results:

Copy Code code as follows:

<div id= "foo" >hello</div><p>i would like to say: </p>

. before () and. InsertBefore ()

3.before ()

Describe:
Inserts a jquery object (similar to an array of DOM elements) before all paragraphs.

HTML Code:

Copy Code code as follows:

<p>i would like to say: </p><b>Hello</b>

JQuery Code:

Copy Code code as follows:

$ ("P"). Before ($ ("B"));

Results:

<b>hello</b><p>i would like to say: </p>


. append () and. Appendto ()

4.append ()

Description: Appends some HTML tags to all paragraphs.

HTML Code:

Copy Code code as follows:

<p>i would like to say: </p>

JQuery Code:

Copy Code code as follows:

$ ("P"). Append ("<b>Hello</b>");

Results:

<p>i would like to say: <b>Hello</b></p>


5.appendTo ()

Description: Creates a new paragraph append div and adds a class

HTML Code:

Copy Code code as follows:

<div></div><div></div>

JQuery Code:

Copy Code code as follows:

$ ("<p/>")
. Appendto ("div")
. addclass ("test")
. End ()
. addclass ("Test2");

Results:

<div><p class= "Test Test2" ></p></div>
<div><p class= "Test" ></p></div>


. prepend () and. Prependto ()

6.prepend ()

Description: Forward a jquery object (similar to an array of DOM elements) to all paragraphs.

HTML Code:

<p>i would like to say: </p><b>Hello</b>

JQuery Code:

$ ("P"). Prepend ($ ("B"));
Results:

<p><b>hello</b>i would like to say: </p>

7.prependTo ()

Description: Appends all paragraphs to an element with an ID value of foo.

HTML Code:

Copy Code code as follows:

<p>i would like to say: </p><div id= "foo" ></div>

JQuery Code:

Copy Code code as follows:

$ ("P"). Prependto ("#foo");

Results:

<div id= "foo" ><p>i would like to say: </p></div>

Summarize

1. InsertAfter () and. After (): Inserts an element from the outside of an existing element
2. InsertBefore () and. Before (): Outside the existing element, insert the element from the front
3. Appendto () and. Append (): Inside an existing element, insert elements from behind
4. Prependto () and. Prepend (): Inside an existing element, insert an element from the front

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.