api of jquery and summary of usage

Keywords: Javascript Attribute JQuery less

Summary of jQuery API and usage

selector

Basic selector

  1. *Universal selector

  2. .class class class selector, an element can have multiple classes (chrome is implemented using the native js function getElementByClassName())

Changing the style of an element using a class selector

<div class="demo"></div>

<script type="text/javascript">
    $('.demo').css({
        border: '3px solid red',
    })
</script>
  1. ElementElement selector, tag name of DOM node (call function getElementByTagName() implementation)

Use element selector to find elements in document, add css Style

<script type="text/javascript">
    $('div').css({
        color: 'skyblue',
    })
</script>
  1. id selector, unique, can only be used once in a file (native js call getElementById() function)

Find id element add style

<div id="demo">demo3</div>

<script type="text/javascript">
    $('#demo').css({
        border: '3px solid skyblue',
    })      
</script>

Hierarchical selector

  1. Child selector (select the child element of the parent element)
<div>
    <p></p>
</div>
<script type="text/javascript">
$('div>p').css({
    border: '3px solid skyblue',
})          
</script>       
  1. Group selector (select all elements that can match)

Select.Demo and #demo, separated by commas

<div class="demo">demo2</div>
<div id="demo">demo3</div>

<script type="text/javascript">
$('.demo, #demo').css({
    border: '2px solid red',
})          
</script>
  1. Descendant selector (select the next element of an element)

Note: All matching elements under this element will be selected

In this case, all the p's will be border-style

<div>
    <p>demo</p>
    <p>demo</p>
    <p>demo</p>
</div>

<script type="text/javascript">
$('div p').css({
    border: '1px solid skyblue',
})          
</script>
  1. Prefix Selector

In this example, select an element with only the class name demo below the div

<div class="demo">demo1</div>
<div class="demo">demo2</div>
<div id="demo">demo3</div>

<script type="text/javascript">
    $('div.demo').css({
        color: 'red',
    })      
</script>
  1. next selector (select only the sibling immediately after)

Note: The relationship between elements must be sibling, not parent-child

This example chooses the first span tag that follows only the p tag, so it changes the style of 1

<p></p>
<span>1</span>
<span>2/span>
<span>3</span>
<script type="text/javascript">
    $('p+span').css({
        border: '2px solid blue',
    })          
</script>
  1. nextAll selector (select all sibling elements that follow)

Same as the fifth next selector, except in a different range

In this example, all span tags after the p tag are selected to change the style

<p></p>
<span>1</span>
<span>2/span>
<span>3</span>

$('p~span').css({
        border: '2px solid blue',
    })

attribute selectors

  1. [attribute]

$('div[title]')
Find all elements whose properties are named title s

In this case, all three div s will be added with the border style

<div title = "demo"></div>
<div title = "demo"></div>
<div title = ""></div>

$('div[title = demo]').css({
    border: '5px solid skyblue',
})
  1. [attribute = value], attribute name = attribute value

$('div[title = demo]')

Find all elements whose title attribute value is demo and style them

This example has only the first and second div s with a border style

<div title = "demo"></div>
<div title = "demo"></div>
<div title = ""></div>

$('div[title = demo]').css({
    border: '5px solid skyblue',
})
  1. [attribute|='value']

Similar to [attribute = value], all elements whose attribute name equals its value are selected

  1. [attribute^='value']^=All elements starting with value

div[title^=demo]
Finding title attributes is an element that starts with demo

In this example, only the first two of the three div s will be selected to change the style

<div title = "demo"></div>
<div title = "demodemo"></div>
<div title = "de"></div>

$('div[title = demo]').css({
    border: '5px solid skyblue',
})
  1. [attribute$='value']$=all elements ending with value

div[title$=demo]

Finding title attributes is an element that ends with demo

In this example, the first three divs of the three divs are selected to change the style

<div title = "demo"></div>
<div title = "demo demo"></div>
<div title = "demodemo"></div>
<div title = "de"></div>

$('div[title $= demo]').css({
    border: '5px solid skyblue',
})
  1. [attribute!='value']

This selector is equivalent to: not([attr=value]) is not

div[title!=demo]

Native dom provides querySelectorAll() to improve query performance

In this example, select the element whose title is not equal to demo, that is, the first and third

<div title = "demo"></div>
<div title = "demodemo"></div>
<div title = "de"></div>

$('div[title != demo]').css({
    border: '5px solid skyblue',
})
  1. [attribute*='value']
    As long as a part of the property name contains the value of the property, it will be selected

div[title*=demo]

In this case, both the first and second divs contain demo, so select the first and second div elements

<div title = "demo"></div>
<div title = "demodemo"></div>
<div title = "de"></div>

$('div[title*=demo]').html('jianmei');
  1. [attribute~='value']
    div[title~=demo] means that the value separated by a useful space in the title property is equal to demo

In this example, both the first and third contain demo, and the second has a space, so the first and third are chosen

_u Note: u If div[title=demo] is used in this example, only the first one is selected

<div title = "demo"></div>
<div title = "de demo"></div>
<div title = "demodemo"></div>
<div title = "de"></div>

$('div[title~=demo]').html('jianmei');

Basic Filter Selector

  1. : The index value of the eq(index) index matching element, starting at 0

eq = equal, equal to the value of index

The div selected in this example is index equal to 0

<div class="demo">demo1</div>
<div class="demo">demo2</div>
<div id="demo">demo3</div>
$('div:eq(0)').css({
    color: 'red',
})
  1. :gt(index)

gt = great than is a value greater than index

In this example, the second and third div isions are selected, with elements index greater than 0 selected

<div class="demo">demo1</div>
<div class="demo">demo2</div>
<div id="demo">demo3</div>
$('div:gt(0)').css({
    color: 'red',
})
  1. :lt(index)

lt = less than that is a value less than index

In this example, the first and second div isions are selected, with elements index less than 0 selected

<div class="demo">demo1</div>
<div class="demo">demo2</div>
<div id="demo">demo3</div>
$('div:lt(2)').css({
    color: 'red',
})
  1. : odd selects the elements whose u index is odd, not in the visual order

In this example, the second and fourth div s are selected, with index es of 1 and 3, respectively.

        <div class="demo">demo1</div>
        <div class="demo">demo2</div>
        <div id="demo">demo3</div>
        <div class="demodemo">demo4</div>

            $('div:odd').css({
                color: 'red',
            })

5.: Eve chooses elements whose u index is even, not in visual order

In this example, the first and third div s are selected, with index es of 0 and 2, respectively.

        <div class="demo">demo1</div>
        <div class="demo">demo2</div>
        <div id="demo">demo3</div>
        <div class="demodemo">demo4</div>

            $('div:even').css({
                color: 'red',
            })
  1. : first equals: eq(0), for better performance, use.filter(':first')

The order at this point is visually visible

Only the first div is selected in this example

        <div class="demo">demo1</div>
        <div class="demo">demo2</div>
        
            $('div:first').html('jianmei');
  1. : last, for better performance. filter(':last')

Only the last div is selected in this example

        <div class="demo">demo1</div>
        <div class="demo">demo2</div>
        
            $('div:last').html('jianmei');
  1. : header selects all the header elements. For better performance, filter(':header')

In this case both h1 and h2 will be selected, changing the style

        <h1>jianmei</h1>
        <h2>jianmei</h2>
        
            $(':header').css({
                background: 'skyblue',
            })
  1. : not() selectors for filtering, but often very complex selectors are built, so the.not() method is used in most cases

Write only the.not(selector) method here

In this case, index is not an odd div, so the first and third divs are selected

        <div class="demo">demo1</div>
        <div class="demo">demo2</div>
        <div id="demo">demo3</div>
        <div class="demodemo">demo4</div>
        
            $('div').not(':odd').css({
                border: '2px solid skyblue',
            })
  1. : lang('language') selects all elements of the specified language

Note: Only the first and second span elements are selected in this example: lang selects the elements containing language or the first matching language, not just those containing language.

        <span lang = "en">1</span>
        <span lang = "en-mei">2</span>
        <span lang = "mei-en">3</span>
        
            $('span:lang(en)').css({
                border: '2px solid red',
            })
  1. : root element selected by root is always html

In this example, an html is added to each p

            <p>demo</p>
            <p>demo</p>
            <p>demo</p>
            
            $('<b></b>').html($(':root')[0].nodeName).appendTo('p');
  1. : target matches elements whose ID and identifier match

For example, given url: http://example.com/#foo

$('p:target');

Elements <p id ='foo'>will be selected

  1. : animated selects all elements that are animating

For better usage, first select elements using a pure CSS selector, then use.filter(":animated")

Content Filtering

  1. : parent selects all parent elements that contain child elements or text

For better performance, first select elements using a pure css selector, then use.filter(':parent')

Note: parent involves child elements that contain text nodes

The first and second divs are selected in this example, because only the third div has no child elements and text nodes

        <div><p></p></div>
        <div> </div>
        <div></div>
        
            $('div:parent').css({
                border: '3px solid skyblue',
            })
  1. empty: Instead of parent, select elements that do not contain child elements

The third div is chosen in this case, because only the third div has no child elements and no text node

        <div><p></p></div>
        <div> </div>
        <div></div>
        
            $('div:empty').css({
                border: '3px solid skyblue',
            })
  1. :has()

$('div:has(p)') Select a div that contains at least one p tag

The first div is selected here, and only the first div contains the p tag

        <div><p></p></div>
        <div></div>
        
            $('div:has(p)').css({
                border: '2px solid skyblue',
            })
  1. : contains(text)text is case sensitive and selects all elements that contain the specified text

$('div:has(mei)') Find all divs that contain Mei

        <div>jian mei</div>
        <div>mei</div>
        
            $('div:contains(mei)').css({
                border: '2px solid skyblue'
            })

Visibility filtering

  1. : Hidden selects all hidden elements

Elements can be considered hidden in several situations:

  • The display value of css is none
  • type = "hidden"
  • The height and width of the element are explicitly set to zero

The elements visibility:hidden and opcity:0 are considered visible because they still occupy document space.

Use: hidden() queries do not take full advantage of the querySelectorAll() method provided by the native DOM to improve performance.For better performance in modern browsers, use.filter(":hidden") instead

In this case, the div is hidden, but the div with hidden elements is selected and displayed after 3s
```js

hidden
        // :hidden
        $('div:hidden').show(3000);
        ```
  1. : visible selects all visible elements

Contrary to hidden usage

            <p>demo</p>
            <p>demo</p>
            <p>demo</p>
            
            $('p:visible').click(function() {
                $(this).css({
                    background: 'skyblue',
                })
            })

Child Element Filter Selector

  1. : first-child selects the first child element under all parent elements

In this example, only the first p below div changes the style

        <div>
            <p>demo</p>
            <p>demo</p>
            <p>demo</p>
        </div>
        
            $('div p:first-child').css({
                'text-decoration': 'underline',
            })
  1. first-of-type selects the first sibling element of all the same element names

Note: In this case, unlike first-child, first-child only chooses the first of the direct lineages. If the first is not, it does not. first-of-type chooses the first sibling element to include as long as it contains it. Here, it chooses the first sibling element of the p tag contained in the div.

        <div>
            <a href=""></a>
            <p>demo</p>
            <p>demo</p>
            <p>demo</p>
        </div>
        
            $('div p:first-of-type').css({
                background: 'red',
            })
  1. : last-child selects the first child element under all parent elements

In this example, only the last p below div changes the style

        <div>
            <p>demo</p>
            <p>demo</p>
            <p>demo</p>
        </div>
        
            $('div p:last-child').css({
                'text-decoration': 'underline',
            })
  1. last-of-type selects the last sibling element of all the same element names

The principle is the same: first-of-type,

        <div>
            <a href=""></a>
            <p>demo</p>
            <p>demo</p>
            <p>demo</p>
        </div>
        
            $('div p:last-of-type').css({
                background: 'red',
            })
  1. :nth-child(index/even/odd/equation)

Index: The matched index value, starting at 1, can be even (even) odd (odd) 2n

Note: Unlike eq(), the eq() index starts at 0

        <div>
            <button></button>
            <button></button>
        </div>
        <div>
            <button></button>
        </div>
        
    $('div:nth-child(2)').click(function () {
                $(this).css({
                    border: '2px solid skyblue',
                });
            });
  1. : only-child If an element is the only child element of its parent element, it is selected, and if the parent element has other elements, it is not selected

In this example, only the second div ide has a unique button, so choose the second, and add the text within the second button:

        <div>
            <button></button>
            <button></button>
        </div>
        <div>
            <button></button>
        </div>
        
            $('div button:only-child').text('alone').css({
                border: '2px solid skyblue',
            }
  1. : nth-of-type() the nth of the child elements with the same label name under the same parent element

index starts with 1 and can be either a string even or odd or an equation: nth-of-type (even),: nth-of-type (4n)

This example selects the second button sibling element within the first div

        <div>
            <button></button>
            <button></button>
        </div>
        <div>
            <button></button>
        </div>
        
            $('div button:nth-of-type(1)').text('alone').css({
                border: '2px solid skyblue',
            }

Form Selector

  1. : button Selects all button elements and elements of type button

In this example, both elements are selected and a move style is added

    <input type="button" value="Input Button"/>
    <button>Button</button>
    
            $(':button').addClass('move');
    
  1. : Checkbox queries do not take full advantage of the querySelectorAll() method provided by the native DOM to improve performance, and [type="checkbox"] is recommended instead
    <input type="checkbox" />
    
            $(':checkbox').wrap("<span style='background-color:red'>");
            ----------------------------------------------------------
            //It's best to write like this
            $('[type = checkbox]').wrap("<span style='background-color:red'>");
  1. : checked matches all checked elements

The third input in the selected state is selected in this example
```js


        $('input:checked').wrap("<span style='background-color:red'>");
        ```
  1. : Disabled matches all disabled elements

Select the first input in this example

    <input type="checkbox" disabled/>
    <input type="checkbox" />
    
            $('input:disabled').wrap("<span style='background-color:red'>");
  1. enabled matches all available elements, as opposed to disabled

Select the second input in this example

    <input type="checkbox" disabled/>
    <input type="checkbox" />
    
            $('input:enabled').wrap("<span style='background-color:red'>");
  1. : focus selects the element that currently gets focus

In this example, the input that currently gets the focus is selected, and the input is of type text, then the style is set

    <input type="text" />
    
            $('input[type = text]').focus(function () {
                $(this).css({
                    background:'red',
                })
            })

Summary:file:image:input:password:radio:reset:select:submit:text

The same is true for elements that select all types of attributes.

Properties/css

attribute

  1. .attr()

attr() sets common attributes, prop() sets unique attributes

Gets or sets the value of the property of the first element in a matching set of elements

If you need to get or set the attribute values for each individual element, you need to rely on a loop of.Each(). map()

In this example, both alt and title attributes are added to img

        <img src="../img/4.jpg" alt="" id="photo">
        
            $('#photo').attr({
                alt: 'jianemi',
                title: 'meimei',
            })
  1. prop()

Gets or sets the attribute value of the first element in a matching set of elements

The.prop() method only gets the attribute value of the first matching element

Prohibit all check boxes on the page

        <input type="checkbox" checked>
        <input type="checkbox">
        <input type="checkbox">
        
            $("input[type='checkbox']").prop({
                disabled: true,
            })

3.removeAttr()

Remove an attribute for each element in the set of matching elements

removeAttr() uses the native js method

Deleting an inline onclick event handler with removeAttr() in ie 8, 9, 11 will not achieve the desired effect, instead of using.prop() to avoid potential problems

Click the button to add or remove the title attribute of the input element after the button, in this case using the Execute Now function

        <button>enable</button>
        <input type="text" title="hello">
        <div id="log"></div>
        
            (function () {
                var inputTitle = $("input").attr("title");
                $("button").click(function () {
                    var input = $(this).next();
                    if(input.attr("title") == inputTitle) {
                        input.removeAttr("title")
                    }else{
                        input.attr("title", inputTitle);
                    }
                    $("#log").html("input title is now" + input.attr("title"));
                });
            })();
  1. .removeprop

Delete an attribute for a matching element in the collection

Note: This method cannot be used to delete native properties, such as cheackede disabled selected

In this example, set a div's numeric property and delete it

Para is directly defined on global objects, that is, on windows, so you can access window.para and directly access para

        <div id="log"></div>
        
            para = $("#log");
            para
                .prop('code', 1234)
                .append('code is:', String(para.prop('code')),'.')
                .removeProp('code')
                // The string added by prop has been deleted at this time
                .append('now code is:', String(para.prop('code')),'.')
  1. val()

Gets the current value of the first element in the set of matching elements. This method does not accept any parameters

The.val method is mainly used to get the values of form elements, such as input select and textarea, and returns undefined when called on an empty set

Example: Get the value of a text box

        <input type="text" value="text">
        <p></p>
        
            // Get the value of the text box
            $("input").keyup(function () {
                // Get the current value
                var value = $(this).val();
                // Add the acquired value to p
                $("p").text(value);
            }).keyup();

val() allows you to pass an array of element values, which is useful when using a jquery object that contains such jquery objects as input select option

Example: When a button is clicked, the button value is displayed in the text box

        <button>feed </button>
        <button>the </button>
        <button>input </button>
        <button type="reset">reset</button>
        <input type="text" value="click a button" lang="en">
        
            $("button").click(function () {
                // Get the text of the button
                var text = $(this).text();
                // Add the captured text to value
                $("input[lang = 'en']").val(text);
            })
            // Click the Reset button
            $("button[type = reset]").click(function () {
                $("input[lang = 'en']").val('click a button');
            })

CSS

  1. addClass() adds one or more style class names specified for each matching element

Add multiple style class names to all matching elements separated by spaces

$("p").addClass('css1 css2')

Usually used with removeClass

$("p").removeClass('css1 css2').addClass('css3')

        <p>jianmei</p>
        <p>meimei</p>
        <p>jianjian</p>
        
            // Add elem style to second p
            $("p:nth(1)").addClass("elem");
  1. css Gets the calculated value of the style attribute of the first element in the set of matching elements or sets one or more css attributes for each matching element
        <p>jianmei</p>
        <p>meimei</p>
        <p>jianjian</p>
        
            // Click on an element to get its background color
            $("p").click(function () {
                var color = $(this).css("background-color");
                $("input").val(color);
            })

Set style, every click of div will change style or restore style

        <div id="log"></div>
        
            // Increase the width of the div
            // Define count, used to count times
            var count = 0;
            $("#log").click(function () {
                // count+1 per click
                count ++;
                if(count % 2 == 0){
                    $(this).css({
                        width: '300px',
                    })
                }else{
                    $(this).css({
                        width: '400px',
                    })
                }
            })
  1. hasClass()

Determines whether any matching element is assigned a given style (class)

        <button>feed </button>
        <button class="elem">the </button>
        <button>input </button>
        
            $("input").hasClass("elem").toString();
  1. removeClass()

Remove one or more styles from each matching element in the collection

Remove elem class from matching elements

        <button>feed </button>
        <button class="elem">the </button>
        <button>input </button>
    
            $("button").removeClass('elem');
            //If removeClass() is followed by (), it represents all style classes that have moved out of the current element
  1. toggleClass()

Adding or deleting one or more style classes for each element in the set of matching elements depends on whether the style class exists or the value of the parameter.

Delete if it exists, add if it does not

        <p>jianmei</p>
        <p class="elem">meimei</p>
        <p>jianjian</p>
        
            $("p").click(function () {
            $(this).toggleClass('elem');
        })

size

  1. .height()

Gets the current calculated height value of the first element in the set of matching elements or sets the height value of each matching element

Note: Height only includes the height and width of the element itself

The difference between.css('height') and.height() is that the latter returns a numeric value without units, the former returns a string with complete units, which is often used when an element's height needs to be calculated.

        <p>jianmei</p>
        <p class="elem">meimei</p>
        <p>jianjian</p>
        
            // Increase the length of P and change the color when you click p
            $("p").click(function () {
                $(this).width(300)
                       .css({
                           cursor: "auto",
                           background: '#90EE90',
                       })
            })
  1. width and height are used in the same way

  2. innerHeight()

Note: The height returned by innerHeight() includes the height of the current element itself + the height of the padding

        <p>jianmei</p>
        <p>jianjian</p>
        <p>jianjian</p>
        
            // Every click innerHeight changes and changes color
            var count = 0;
            $("p").click(function () {
                count ++;
                if(count % 2 == 1) {
                    $(this).innerHeight(50).addClass('elem');
                }
                else {
                    $(this).innerHeight(30).addClass();
                }
                })
  1. innerWidth and innerHeight are used in the same way

5.outerHeight()

Gets or sets the current calculated outer height of the first element in a matching set of elements

The height of outerHeight includes: its own height + padding + border + (margin)

Margin is optional when outerHeight(true), including margin

        <p>jianmei</p>
        <p>jianjian</p>
        <p>jianjian</p>
        
            var oheight = 60;
            $("p").click(function() {
                $(this).outerHeight(oheight).addClass('elem');
                // Reduce 4 per click
                oheight -= 4;
            })
            
            var oheight = 60;
            $("p").one('click', function() {
                $(this).outerHeight(oheight).addClass('elem');
                // One-click effect
                oheight -= 4;
            })

position

  1. .offset()

In the set of matching elements, get the current coordinates of the first element, or set the coordinates of each element relative to the document

Click to see the location of the current element

        <p>jianjian</p>
        <div id="log"></div>
        
            $('#log', document.body).click(function (e) {
                var offset = $(this).offset();
                // Prevent Event Bubbles
                e.stopPropagation();
                $('p').text(offset.left + ', ' + offset.top);
            }); 
  1. .position()

The difference with offset is that position is the displacement of i relative to the parent element, and offset is more appropriate if you want to get the location of this new element

        <p>jianjian</p>
        <div id="log"></div>
        
            $('#log').click(function (e) {
                var position = 
                $('p').text(position.left + ', ' + position.top);
            })
  1. offsetParent()

Gets the closest ancestor element with positioning information to a specified element. An element with positioning information refers to:

The position property of css is a relative absolute or fixed element

        <ul>
            <li>22
                <ul>
                    <li style="position: relative;">1</li>
                    <li class="elem">2</li>
                    <li>3</li>
                </ul>
            </li>
        </ul>
        
            $('li.elem').offsetParent().css('background-color', 'red');
  1. scrollLeft()

Gets the current horizontal scrollbar position of the first element in the set of matching elements or sets the horizontal scrollbar position for each matching element

Get scrollLeft of div

The distance of the current div horizontal scrollbar is known in this example

        <div id="log"></div>
        
            $('#log').text('scrollLeft:' + $(this).scrollLeft());
  1. scrollTop()

Gets the current vertical scrollbar position of the first element in the set of matching elements or sets the vertical scrollbar position for each matching element

The distance of the current div vertical scrollbar is known in this example

        <div id="log"></div>
        
            $('#log').text('scrollTop:' + $(this).scrollTop());

data

  1. .data()

Stores any related data on a matching element or returns the value of the data store with the given name of the first element in the set of matching elements

.data(obj) A key/value pair for updating data

The.data() method allows us to bind any type of data on the dom element again, avoiding the risk of memory leaks from circular references

Store and retrieve a value from the div element

In this example, the data stored in #log can be extracted into the space separately

        <div id="log">
            the value is 
            <span></span>
            and
            <span></span>
        </div>
        
            $('#log').data('test', {
                first: 16,
                last: 'jianmei',
            });
            //Add first content of test to #log
            $('span:first').text($('#log').data('test').first);
            $('span:last').text($('#log').data('test').last);
  1. .removeData()

Remove bound data on elements

.removeData([name]), the name of the stored data to be removed

.removeData([list]), an array or a space-delimited string names the data block to be deleted

        <div id="log">
            the value is 
            <span></span>
            and
            <span></span>
        </div>
        
            $('#log').data('test1', {
                first: 16,
            });
            $('#log').data('test2', {
                last: 'jianmei',
            });
            $('span:first').text($('#log').data('test1').first);
            //Remove test1 data bound to #log
            $('#log').removeData('test2');
            $('span:last').text($('#log').data('test2').last);

operation

Copy

clone creates a deep copy of a matching set of elements

The.clone() method copies in depth all matching element collections, including all matching elements, subelements of elements, and text nodes

When used in conjunction with the insert method,.clone() is convenient for copying elements on a page

_u Note_u: When using clone, we can modify the cloned element or element content before inserting it into the document

Copy all b elements and insert them into all paragraphs

        <b>hello</b>
        <p>have a good day</p>
        
            // prependTo is to insert elements before
            // $('b').clone().prependTo('p');
            // appendTo is the insertion of an element after, meaning add
            $('b').clone().appendTo('p');

DOM Insert, Package

  1. .wrap()

Wrap an html structure around each matching element in the collection

Wrap a div outside all p's, in this case there will be two divs

        <p>have a good day</p>
        <p>have a nice day</p>
        
        //Wrap a div with class demo outside p
            $('p').wrap("<div class = 'demo'></div>")
  1. wrapAll()

Wrap an html element outside all matching elements in the collection. In this case, only one div wrapped outside two p elements is angry, and the number of divs is only one

        <p>have a good day</p>
        <p>have a nice day</p>
        
            // Unlike wrap, wrap adds a div to every element that matches
            // WapAll adds only one div to all matching elements        
            $('p').wrapAll("<div class = 'demo'></div>")
  1. wrapInner()

Outsourcing a structure of content within matching elements

Select all paragraphs and wrap the contents of each matching element

Note: wrap and wrapInner are both wrapping each matching element

The difference is that wrap wraps one layer around each element selected, but wrapInner wraps one layer around the content of each element selected

        <p>have a good day</p>
        <p>have a nice day</p>
        
        //What was packed was content have a good day
            $('p').wrapInner("<div class = 'demo'></div>")

DOM Insert, Internal Insert

  1. append()

Insert parameter content at the end of each matching element

        // Insert p into div
            $('div').append($('b'));
  1. appendTo()

Insert the matching element at the end of the target element

        <b>hello</b>
        <div class="demo"></div>
        
        // Insert p into div
            $('b').appendTo($('.demo'));
  1. html()

Gets the html content of the first matching element in the collection or sets the html content of each matching element

        <div class="demo">123</div>
        <div class="demo">123</div>
        <div class="demo">123</div>
        
            // If an empty string is added, it means emptying the contents of the div
            // $('.demo').html('');
            // Add content to div
            $('.demo').html('jianmei');

4.prepend()

Insert the parameter content before each matching element (inside the element)

        <b>hello</b>
        <div class="demo">123</div>
        
            // Insert b within div
            // The content of element b is placed in front of the original div content, which is the opposite of append
            $('.demo').prepend($('b'));
  1. prependTo()

Insert all elements in front of the target (within the element)

        <b>hello</b>
        <div class="demo">123</div>
        
            // Insert b into div
            $('b').prependTo($('.demo'));
  1. text()

Gets the text content of each element in the set of matching elements, including their descendants, or sets the text content of each element in the set of matching elements to the specified text content

        <p>have a good day</p>
        <p>have a nice day</p>
        
            // Add text to paragraph p
            $('p').text('jianmeinew text');

DOM Insert, External Insert

1,after()

Inserts the content specified by the parameter after each element in the set of matching elements as its sibling node

        <div class="demo">123</div>
        <div class="demo">123</div>
        
            // Insert p tag after demo class
            // $('.demo').after('<p>jianmei</p>')
            // Insert all p after demo class
            $('.demo').after($('p'));

2. The theory of before and after is the same. Depending on the setting of the parameters, insert the content before the matching element and insert the outside

            // Insert p tag before demo class
            $('.demo').before('<p>jianmei</p>')

3. InsrtAfter and after are the same functions, mainly because the insertion content and target location are different.

            //Insert p after demo class
            $('p').insertAfter('.demo');

4. Similarly, we can see the principle of insertBefore

            // Before inserting p into demo class
            $('p').insertBefore('.demo');

DOM Removal

1. detach(), removing all matching elements from the DOM

detach is the same as remove except deach, which holds all jquery data associated with the removed element

This method is commonly used when you need to move a piece of data and insert the element into the DOM soon.

        <p>hello</p>
        <p>you</p>
        <button>meimei</button>
        
            // Delete all paragraphs in DOM
            $('p').click(function () {
                $(this).toggleClass('.off');
            });
            var p;
            $('button').click(function () {
                if(p) {
                    p.appendTo('body');
                    p = null;
                    }else {
                        p = $('p').detach();
                    }
            });

2. remove() deletes the set of matching elements from the DOM (along with events on the elements and jquery data)

You can remove any element you want to remove

Move all paragraphs from DOM

            // Delete all paragraphs from DOM
            $('button').click(function () {
                $('p').remove();
            })

3. empty() removes all child nodes of matching elements from the set from the DOM

This method removes not only child and descendant elements, but also text from elements

        <p>hello</p>
        <p>you</p>
        <button>meimei</button>
        
        $('button').click(function () {
            $('p').empty();
        });

4. unwrap() deletes the parent element of the set of matching elements, leaving itself (and sibling elements, if any) in its original position

Add or remove a div at the outside of each paragraph

Click the button to add or remove styles

        <p>hello</p>
        <p>you</p>
        <button>meimei</button>
        
            // Click the button to add and delete demo-style parent elements of p
            var pTags = $('p');
            // Bind event to button
            $('button').click(function () {
                // Determine if the parent element of p has a demo style
                // Delete if available
                if(pTags.parent().is('.demo')) {
                    pTags.unwrap();
                }
                // Wrap a demo-style div if not
                else{
                    pTags.wrap('<div class = "demo"></div>');
                }
            });

DOM Replacement
1, replaceAll()

Replace each target element with a set's matching elements

.replaceAll(target)

            // Replace all p with demo
            $('button').click(function () {
                $('<div class = "demo">div</div>').replaceAll($('p'));
            })

2, replaceAll()

Replace all matching elements in the set with the provided content and return the set of deleted elements

.replaceWith() can remove content from the dom or insert new content here

            // Replace the button with div when you click the button
            $('button').click(function () {
                // Replace current button with div
                $(this).replaceWith("<div class = 'demo'>" + $(this).text() + "</div>");
            })

Event

Browser Events

1, .resize()

Bind a handler for the resize event of the js, or trigger the event on the element

Example: When the window size changes (after changes), view the width of the window.

            $(window).resize(function () {
                $('body').prepend('<div>' + $(window).width() + '</div>');
            })

2, .scroll()

Bind a handler to the scroll event of the js, or trigger the event on the element

Example: Trigger a series of actions as the page scrolls

            $('p').clone().appendTo(document.body);
            $('p').clone().appendTo(document.body);
            $('p').clone().appendTo(document.body);
            $('p').clone().appendTo(document.body);
            $('p').clone().appendTo(document.body);
            $(window).scroll(function () {
                $('span').css({
                    'display':'inline'
                }).fadeOut('slow');
            })

3. Document loading (holdReady())

Pause or resume, delaying readiness events until loaded

            $.holdReady(true);
            $.getScript(''),function () {
                $.holdReady(false);
            };

3, ready()

When the dom is ready, specify a function to execute

Example: Display information when the dom loads

            $(document).ready(function () {
                $('p').text("the dom is")
            })
            //When the dom is ready, a function is bound
            $(document).ready(function () {
                // Bind a function to button, click button, toggle p's up and down state
                $('button').click(function () {
                    $('p').slideToggle();
                });
            })

4,unload()

Bind a handler for js unload event

Example: Display a prompt box when leaving the page

            $(window).unload(function () {
                return "bye now";
            });

Event Binding

1, bind()

Bind an event handler to an element

Basic use of bind: bind a click event to p

$('p').bind('click', function () { alert('user clicked'); })

Example: Bind click events for paragraph labels

        <p>ppp </p>
        <span></span>
        
            // Click p to write the location of the mouse click into the space
            // Change class style when mouse moves in and out
            $('p').bind('click', function (event) {
                $('span').text('clicked:' + event.pageX + ',' +  event.pageY);
            })
            $('p').bind('mouseenter mouseleave', function (event) {
                $(this).toggleClass('demo');
            })

2, delegate()

Bind one or more event handlers to all elements of the matching selector, based on a specified subset of root elements, which include those elements that are currently matched as well as those that may be matched in the future.

Example: Click to add another paragraph. Note that delegate() binds a click event to all paragraphs, or even a new paragraph.

            // delegate()
            // Click on a click event for P. Each click adds a style p to the back of the previous one
            $('body').delegate('p', 'click', function () {
                $(this).after('<p>new paragraph</p>')
            });

3, off()

Remove an event handler

Example: Remove click events

        <p>ppp </p>
        <p>After removal</p>
        <button>remove</button>
        
            // ready(), loads the background color when the dom is ready
            $(document).ready(function () {
                $('p').on('click', function () {
                    $(this).css('background-color', 'pink');
                });
                // After clicking button to remove click events, no events are bound
                $('button').click(function () {
                    $('p').off('click');
                });
            })
  1. one()

Adds a handler for an element's events, which is executed at most once per event type on each element

one() is the same as on(), except that for a given element and event type, the handler is unbound immediately after the first trigger of the event

Example: Click on any paragraph and the font size of the paragraph will only change once

            // Here is one, so this event only executes once, the click effect is only valid once, if it is an on-binding event, normal state can click more than once to achieve the effect
            $(document).ready(function () {
                $('p').one('click', function () {
                    $(this).animate({
                        fontSize: "+=6px"});
                });
            });
  1. trigger()

trigger() differs from triggerHandle(): trigger triggers the default event

Execute all handlers and behaviors based on the given event type bound to the matching element

        <input type="text" value="text">
        <button type="button">Selected</button>
        
            // Click button to select the text of the input box
            $('input').ready(function () {
                $('button').click(function () {
                    $('input').trigger('select');
                })
            })
  1. triggerHandle() is similar to the trigger method except that trigger triggers the default behavior of events, such as form submission.

Form Events

  1. blur()

A blur event occurs when an element loses focus, which is often used with focus

            // When input loses focus, a prompt box pops up
            $(document).ready(function () {
                $('input').blur(function () {
                    alert('Lost focus');
                })
            })
  1. The focus() and blur() methods are used similarly
            // Show prompt when getting focus
            $(document).ready(function () {
                $('input').focus(function () {
                    $('span').css({
                        'display':'inline',
                    }).fadeOut(2000);
                })
            })
  1. change() A change event occurs when an element's value changes (only for form fields)

When the value of the input box changes, pressing the enter key or clicking outside the input box will bring up a prompt box

            $(document).ready(function () {
                $('input').change(function () {
                    alert('Text has been modified');
                })
            })
  1. select()

Bind a handler for the js select event

Example: Display text within a div when the text of an input box is selected

            $(document).ready(function () {
                $('input').select(function () {
                    $('div').text('select').show().fadeOut(2000)
                })
            })
  1. submit()

When a form is submitted, a submit event occurs, which applies only to the form element

        <form action="505-Event Bubbling.html" method="post">
            <input type="text">
            <input type="text">
            <input type="submit" value="Submit"/>
        </form>
        
            $(document).ready(function () {
                $('form').submit(function () {
                    alert('Submit');
                });
            });

Keyboard events

  1. keydown() and keyup()

Order of events related to keydown events

* The process in which the keydown key is pressed
 * The keypress key is pressed
 * The keyup key is released

Example: Pressing the keyboard changes the color of the input box ()

            $(document).ready(function () {
                $('input').keydown(function () {
                    $('input').css({
                        'background-color':'red',
                    });
                });
                $('input').keyup(function () {
                    $('input').css({
                        'background-color':'green',
                    })
                })
            });
  1. keypress()

Example: Calculate the number of keystrokes in the input field

            var i = 0;
            $(document).ready(function () {
                $('input').keypress(function () {
                    $('span').text(i += 1);
                })
            })

Mouse events

  1. click() single click dblclick() double click

2. Mouse-related events

            $(document).ready(function () {
                $('div').mousedown(function () {
                    $(this).css({
                        'border':'2px solid blue',
                    });
                }).mouseout(function () {
                    $(this).css({
                        'border':'4px solid green',
                    })
                }).mouseover(function () {
                    $(this).css({
                        'background':'pink',
                    })
                }).mouseleave(function () {
                    $(this).css({
                        'background':'darkgrey',
                    })
                }).mouseenter(function () {
                    $(this).css({
                        'background' :'red',
                    })
                }).onmouseup(function () {
                    $(this).css({
                        'background' :'blue',
                    })
                })
            })
  1. mousemove()
            // Gets the position of the mouse on the page when the mouse moves
            $(document).ready(function () {
                $(document).mousemove(function (event) {
                    $('span').text(event.pageX + ',' + event.pageY);
                });
            });
  1. focusin() and focusout()

The focusin event occurs when an element or any element within it gains focus

Example: Set the background color of a div element when the div element or any of its subelements is focused

            // focusin() and focusout
            $(document).ready(function () {
                $('nav.demo').focusin(function () {
                    $(this).css({
                        'background' : 'red',
                    });
                });
                $('nav.demo').focusout(function () {
                    $(this).css({
                        'background' : '#90EE90',
                    })
                })
            })

Event Object

1,event.currentTarget

This property is the current dom element during the event bubble phase and is usually equal to this

    $(document).ready(function () {
                $('button, div, p').click(function () {
                    // Since there are three equal signs, which are equivalent to judgment, the output value hi is a Boolean value, event.currentTarget is equal to this, so it returns true
                    alert(event.currentTarget === this);
                });
            });

2,event.data()

Optional data to be passed to the event method when the handler currently executing is bound

Example: Return data passed through the on method for each p element

Not understood here yet

            $(document).ready(function () {
                $('p').each(function (i) {
                    $(this).on('click',{x:i},function (event) {
                        // index starts at 0
                        alert('num:' + $(this).index() + ',' + event.data.x);
                    });
                });
            });

3,event.isDefaultPrevented()

Check if preventDefault() is called by the specified event

Example: Prevent links from opening URLs and check if preventDefault is called

            $(document).ready(function () {
                $('nav').click(function(event) {
                    event.preventDefault();
                    // Returns true if called
                    alert('Whether to call:'+ event.isDefaultPrevented());
                });
            });

4. event.pageX and event.pageY

Returns the position of the mouse relative to the left and top edges of the document

Example: Get the location of the mouse

            $(document).ready(function () {
                $(document).mousemove(function (event) {
                    $('nav').text("x:" + event.pageX  +"y:" + event.pageY);
                })
            })

5, event.preventDefault()

Prevent elements from taking default actions: for example, when clicking Submit, block submission of the form, and block url links.

Example: Prevent links from opening URLs

            $(document).ready(function () {
                $('a').click(function (event) {
                    event.preventDefault();
                });
            });

5. event.which returns the mouse button or button that was pressed on the specified event

Example: When you enter something in the input box above, you get stuck in the number code of the input key in the div.

            $(document).ready(function () {
                $('input').keydown(function (event) {
                    $('div').html('key:' + event.which);
                })
            })

Effect

Basics

1. hide() and show()

Hide selected elements, similar to css3's display:none, hidden elements are not fully displayed and do not affect the layout

Example: Click the button to hide/show all p elements

        <p>hide/Displayed Paragraphs</p>
        <button type="button" class = "btn1">hide</button>
        <button type="button" class = "btn2">display</button>
        
            $(document).ready(function () {
                $('.btn1').click(function () {
                    $('p').hide();
                });
                $('.btn2').click(function () {
                    $('p').show();
                });
            })

2, toggle()

The toggle method adds two or more functions in response to switching between click events for the selected element

Example: Click on the p element to switch colors

        <button type="button" class="btn3">toggle</button>
        
            $('.btn3').click(function () {
                $('p').toggle(function () {
                    $(this).css({
                        'background':'red',
                    });
                });
            })

custom

1, animate()

This method changes an element from one state to another through a css Style

Note: Relative animations are generally created using'+=''-='

Example: Animate elements by changing their height

        <button type="button" class="btn4">Increase Height</button>
        <button type="button" class="btn5">Reset Height</button>
        <div></div>
        
            $(document).ready(function () {
                $('.btn4').click(function () {
                    $('div').animate({
                        'height': '300px',
                    });
                });
                // Reset
                $('.btn5').click(function () {
                    $('div').animate({
                        'height': '150px',
                    });
                });
            })

2, delay()

Setting delay for next item in queue

Example: Hide and show two more divs, where the green div has a second delay before it is displayed

        <button type="button" class="btn6">delay run</button>
        <div class="item1"></div>
        <div class="item2"></div>
        
    $(document).ready(function () {
                $('.btn6').click(function () {
                    //SlideUp (300), retrieve div after 300 milliseconds, enter 800ms
                    $('.item1').slideUp(300).fadeIn(800),
                    $('.item2').slideUp(300).delay(1000).fadeIn(800);
                });
            });

3. dequeue() and queue()
The dequeue() method removes the next function from the queue and executes the function, which is one or more functions waiting to be run, usually in conjunction with the queue method

The queue() method displays the queue of functions to be executed on the selected element

Example: Remove the next function from the queue and execute the function

Note: The dequeue() method must be guaranteed to be called within the function added by queue(), or simply, the dequeue() function must be guaranteed to have dequeue()

        <button type="button" class="btn7">run</button>
        <div class="item1"></div>
        
            $(document).ready(function () {
                $('.btn7').click(function () {
                    var item1 = $('.item1');
                    item1.animate({
                        'height':'200',
                        'width':'200',
                    },'slow');
                    //Execution Queue
                    item1.queue(function () {
                        //css changes are not necessary, but dequeue() must be within the queue() method
                        item1.css({
                            'background' :' pink',
                        });
                        item1.dequeue();
                    });
                    item1.animate({
                        'height':'100',
                        'width':'100',
                    },'slow');
                })
            })

4, finish()

Stop the currently running animation, remove all queued animations, and complete all animations for the selected element

        <button type="button" class="btn8">start</button>
        <button type="button" class="btn9">stop</button>
        <div class="item1"></div>
        
            $(document).ready(function () {
                $('.btn8').click(function () {
                    $('.item1').animate({
                        'height':'200'
                    },2000);
                    $('.item1').animate({
                        'width':'200'
                    },2000);
                });
                $('.btn9').click(function () {
                    $('.item1').finish();
                });
            });

5, stop()

The selected element stops the currently running animation

The principle is similar to finish, except that finish stops the current animation and completes the entire animation process, whereas stop is equivalent to pressing the pause key to stop the current animation, and clicking on the start will follow the previous animation track.

Gradient

1. fadeIn and fadeOut

in is the process of gradually changing the opacity of the selected element from hidden to visible

Out is the process of going out from being visible to being hidden

        <button type="button" class="btn10">Fade in</button>
        <button type="button" class="btn11">Fade out</button>
        <br>
        <div class="item2"></div>
        
            $('.btn10').click(function () {
                $('.item2').fadeIn(1000);
            });
            $('.btn11').click(function () {
                $('.item2').fadeOut(1000);
            })

2, fadeToggle()

You can switch between fadeIn and fedeOut, and if the element has faded out, it will be added with the fade out effect, and vice versa.

        <button type="button" class="btn12">Fade in/Fade out</button>
        <div class="item1"></div>
        
            // Clicking on the button will automatically determine the fade-in and fade-out status of the current element
            $(document).ready(function () {
                $('.btn12').click(function () {
                    $('.item1').fadeToggle(3000);
                })
            })

3,fadeTo()

Allow gradients to be given opacity (0,1)

        <button type="button" class="btn13">Dim colour</button>
        <br>
        <div class="item2"></div>
        <div class="item1"></div>
        
            $(document).ready(function () {
                $('.btn13').click(function () {
                    $('.item1').fadeTo('1000', 0.45);
                    $('.item2').fadeTo('2000', 0.15);
                })
            })

Slide

1. slideDown() and slideUp()

down: Show selected elements in sliding mode, show off

up: Hide selected elements by sliding, hide hidden

        <button type="button" class="btn14">hide</button>
        <button type="button" class="btn15">display</button>
        <br>
        <div class="item1"></div>
        
            $(document).ready(function () {
                $('.btn14').click(function () {
                    $('.item1').slideUp(2000);
                });
                $('.btn15').click(function () {
                    $('.item1').slideDown(2000);
                });
            })

2,slideToggle()

Switch between slideUp and slideDown on the selected element

        <button type="button" class="btn16">hide/display</button>
        
            $(document).ready(function () {
                $('.btn16').click(function () {
                    $('.item1').slideToggle(1000);
                });
            });

Posted by bizerk on Thu, 19 Sep 2019 18:42:14 -0700