Home > Web Front-end > JS Tutorial > body text

Summary of jquery common methods and usage examples_jquery

WBOY
Release: 2016-05-16 16:31:58
Original
1438 people have browsed it

mouseover()/mouserout()

Mouseover/mouseout events are triggered when the mouse enters/leaves an element or its descendant elements.
The mouseover event is most often used together with the mouseout event.

Due to the bubbling mechanism, mouseover/mouserout events are often accidentally triggered when not needed, causing some script problems.

mouseenter()/mouseleave()

mouseenter/mouseleave is triggered when and only when the mouse enters the selected element. It will not be triggered when the mouse passes through any child elements. It doesn't care whether the target element has children.

focusin() and focusout()

.focusin(): This event is triggered when an element or its sub-elements receive focus
.focusout(): This event is triggered when an element or its child elements lose focus

Unlike the focus() method, the focusin() method is also triggered when any child element gets focus.

Copy code The code is as follows:


focusin fire


focusin fire


<script><br> $( "p" ).focusin(function() {<br> $( this ).find( "span" ).css( "display", "inline" ).fadeOut( 1000 );<br> });<br> </script>

eq() and get()

.get(): Get a corresponding DOM element through the jQuery object.
.eq(): Constructs a new jQuery object from an element of the collection

eq returns a jQuery object, and get returns a DOM object. For example:

$( "li" ).get( 0 ).css("color", "red"); //Error
$( "li" ).eq( 0 ).css("color", "red"); //Correct
So, what is a DOM object and what is a jQuery object?

The DOM object is an object obtained using js, and the juqery object is an object obtained using the selector of the jQuery class library.

For example: var $obj = $("div");//jQuery object

The get method essentially converts the jQuery object into a DOM object, but css belongs to the jQuery constructor, and this method does not exist in DOM. If we need to use the jQuery method, we must write like this:

Copy code The code is as follows:

var li = $("li").get(0);
$(li).css("color","black");//Wrap with $

filter()

filter() method: Filter out the set of elements that match the specified expression.
This method is used to narrow the scope of matching. Separate multiple expressions with commas.

filter(expression): (String|Function) If the parameter is a string, a jQuery selector is formulated to remove all elements that do not match the selector from the packaging set, leaving only those elements that match the selector. Element; used to determine filter criteria if the argument is a function. This function is called once for each element in the wrapping set. Any element that returns false from the function call will be deleted from the wrapping set.

The following code means: retain the first and element with select class

HTML code:

Copy code The code is as follows:

Hello

Hello Again

And Again


jQuery code:

Copy code The code is as follows:

$("p").filter(".selected, :first")

Result:

Copy code The code is as follows:

Hello

,

And Again


Look at another example of a function, a function 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 functions, this refers to the current DOM element.

HTML code:

Copy code The code is as follows:

  1. Hello

How are you?


jQuery code:

Copy code The code is as follows:

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

Result:

Copy code The code is as follows:

How are you?


.bind(), .live() and .delegate() methods

.bind(): The most basic way to bind event handling functions is to use the .bind() method. It is the same as the live() method, accepting two parameters:

.bind(event type, event handler)
Two ways to bind event handlers:

Copy code The code is as follows:

$(document).ready(function(){
$('.mydiv').bind('click',test);

function test(){
alert("Hello World!");
}
});

Event handlers can also use anonymous functions, as shown below:

Copy code The code is 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() not only acts on elements currently existing in the DOM, but also acts on elements that may exist (dynamically generated) in the future

Copy code The code is as follows:

$(document).ready(function(){
           $('.box').live('click',function(){
                $(this).clone().appendTo('.container');
        });
});


                                                                                                                     


The disadvantage of using the live method to bind events is that it cannot use chained calls. Is there a method that can not only bind events like the live method but also support chained calls? The answer is the delegate method below.

delegate() method: Add one or more event handlers to the specified element (a child element of the selected element),

And specify functions to run when these events occur. Starting with jQuery 1.7, .delegate() has been replaced by the .on() method.
Syntax:

$(selector).delegate(childSelector,event type,function)

Parameter description:

childSelector required. Specifies one or more child elements to which event handlers are attached.

event required. Specifies one or more events to attach to the element. Multiple event values ​​separated by spaces. Must be a valid event.

function required. Specifies a function to run when an event occurs.

Copy code The code is as follows:

$(document).ready(function(){
           $('.container').delegate('.box','click',function(){
                $(this).clone().appendTo('.container');
        });
});

delegate() will be used in the following two situations:

1. If you have a parent element and need to add events to its child elements, you can use delegate(). The code is as follows:

Copy code The code is 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 packaging set.
Each filtering method is pushed onto the stack. When we need to return to the previous state, we can use end() to perform a pop 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 its previous state.

Copy code The code is as follows:





In the above code example, we will only see that the font color of item 1 has changed, but the background color has not changed. This is because
The state before the second find() method returned an object with a class value of two in red font. Therefore, the second find() will only search for .two in

    . Use The end() method modifies the code of the chain operation as follows:

    Copy code The code is as follows:


    The

    end() method here returns the state before calling find(), which is $('ul.one')

    toggleClass()

    `toggleClass() method: `If the specified class name does not exist in the element, add the specified class name; if the element already has the specified
    class name, removes the specified class name from the element.
    css(name,value) method: Set the specified value to the specified css style attribute of each matched element

    wrap() and wrapInner()

    `wrap() and wrapInner(): `The former wraps all matching elements with the structured tags of other elements;
    The latter wraps the sub-content (including text nodes) of each matching element with an HTML structure.
    Look at the following example of wrap():
    Use the content of the original div as the class of the new div and wrap each element

    HTML code:

    Copy code The code is as follows:


    Hello

    Goodbye


    jQuery code:

    Copy code The code is as follows:

    $('.inner').wrap(function() {
    return '
    ';
    });

    Result:

    Copy code The code is as follows:



    Hello



    Goodbye



    Then look at the following example of wrapInner():

    Use the content of the original div as the class of the new div and wrap each element

    HTML code:

    Copy code The code is as follows:


    Hello

    Goodbye


    jQuery code:

    Copy code The code is as follows:

    $('.inner').wrapInner(function() {
    return '
    ';
    });

    Result:

    Copy code The code is as follows:



    Hello



    Goodbye



    detach, empty and remove methods

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

    .empty(): This method not only removes child elements (and other descendant elements), but also removes the text within the element. Because, according to the instructions, any text string in the element is regarded as a child node of the element.

    .remove( [selector ] ): Remove the element from the DOM and remove the events and jQuery data on the element

    Example of empty():

    Copy code The code is as follows:


    • item 1

    • item 2

    • item 3


    Look at the following remove() example:

    Description: Delete all paragraphs from DOM

    HTML code:

    Copy code The code is as follows:

    Hello

    how are

    you?


    jQuery code:

    Copy code The code is as follows:

    $("p").remove();

    Result:

    how are
    val() method

    val(): Get the current value of the matching element.
    Description: Get the value in the text box

    jQuery code:

    Copy code The code is as follows:

    $("input").val();

    jQuery code:

    Copy code The code is as follows:

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

    each() and map()

    each() and map() methods: each returns the original array and does not create a new array. The map method will return a
    new array. If map is used unnecessarily, memory may be wasted.
    each method:

    Define an empty array and add ID values ​​to the array through the each method; finally, after converting the array into a string, alert the value;

    Copy code The code is as follows:

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

    map method:

    Execute return this.id for each :checkbox; and automatically save these return values ​​as jQuery objects, then use the get method to convert them into native Javascript arrays, then use the join method to convert them into strings, and finally alert This value;

    Copy code The code is as follows:

    $(function(){
    var str = $(":checkbox").map(function() {
             return this.id;
    }).get().join();  
    alert(str);
    })

    When you need the value of an array, use the map method, which is very convenient.

    For a more detailed discussion, please click on my other article: Detailed explanation of the use of jQuery’s built-in functions map() and each()

    $.each()

    jQuery’s $(selector).each() function can traverse the selected child elements of the loop, while jQuery’s $.each() function can traverse any collection, including objects and arrays. It receives the collection to be traversed and a Callback function, the callback function passes an array subscript and the value of the array corresponding to the subscript each time.

    $.each(array,callback);

    $.each(object,callback);
    Array instance

    Copy code The code is 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: Execute all handlers and actions based on the given event type bound to the matching element.

    Any event handler bound via .on() or a shortcut method will be triggered when the corresponding event occurs. However, they can be triggered manually using the .trigger() method

    Copy code The code is as follows:


    .attr() and .prop()

    .attr(): Get the value of the attribute of the first element in the matched element set or set one or more attributes of each matching element.

    .prop(): Same as above
    Before jQuery 1.6, the .attr() method would return the value of property when taking the value of certain attributes, which led to inconsistent results. Starting from jQuery 1.6, the .prop() method returns the value of the property, and the .attr() method returns the value of the attributes.

    For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved or assigned using the .prop() method.

    They do not have corresponding attributes, only properties.

    .after() and .insertAfter()

    1.after()

    Description:
    Insert a jQuery object (similar to an array of DOM elements) after all paragraphs.

    HTML code:

    Copy code The code is as follows:

    Hello

    I would like to say:


    jQuery code:

    Copy code The code is as follows:

    $("p").after( $("b") );

    Result:

    Copy code The code is as follows:

    I would like to say:

    Hello

    2.insertAfter()

    Description:
    Insert all paragraphs after an element. Same as $("#foo").after("p")

    HTML code:

    Copy code The code is as follows:

    I would like to say:

    Hello

    jQuery code:

    Copy code The code is as follows:

    $("p").insertAfter("#foo");

    Result:

    Copy code The code is as follows:

    Hello

    I would like to say:


    .before() and .insertBefore()

    3.before()

    Description:
    Insert a jQuery object (similar to an array of DOM elements) before all paragraphs.

    HTML code:

    Copy code The code is as follows:

    I would like to say:

    Hello

    jQuery code:

    Copy code The code is as follows:

    $("p").before( $("b") );

    Result:

    Hello

    I would like to say:


    .append() and .appendTo()

    4.append()

    Description: Append some HTML tags to all paragraphs.

    HTML code:

    Copy code The code is as follows:

    I would like to say:


    jQuery code:

    Copy code The code is as follows:

    $("p").append("Hello");

    Result:

    I would like to say: Hello


    5.appendTo()

    Description: Add a new paragraph to the div and add a class

    HTML code:

    Copy code The code is as follows:


    jQuery code:

    Copy code The code is as follows:

    $("

    ")
    .appendTo("div")
    .addClass("test")
    .end()
    .addClass("test2");

    Result:



    .prepend() and .prependTo()

    6.prepend()

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

    HTML code:

    I would like to say:

    Hello

    jQuery code:

    $("p").prepend( $("b") );
    Result:

    HelloI would like to say:

    7.prependTo()

    Description: Append all paragraphs to the element with ID value foo.

    HTML code:

    Copy code The code is as follows:

    I would like to say:


    jQuery code:

    Copy code The code is as follows:

    $("p").prependTo("#foo");

    Result:

    I would like to say:

    Summary

    1. .insertAfter() and .after(): Insert elements from behind outside existing elements
    2. .insertBefore() and .before(): Insert elements from the front outside the existing elements
    3. .appendTo() and .append(): insert elements from behind inside existing elements
    4. .prependTo() and .prepend(): insert elements

    from the front inside existing elements
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template