JQuery application (2) use jQuery to manage selection results (recommended), jquery

Source: Internet
Author: User
Tags element groups

JQuery application (2) use jQuery to manage selection results (recommended), jquery

The elements selected by jQuery are very similar to arrays. They can be processed using a series of methods provided by jQuery, including length, searching for an element, and intercepting a paragraph.

1. Obtain the number of elements.

In jQuery, you can use the size () method to obtain the number of elements in the selector. It is similar to the length attribute in the array and returns an integer. For example:

$("img").size()

Obtain the number of images on the page.

The following is an example. You can click to add a div block and calculate the <div> block on the page.

<Style> div {border: 1px solid #003a75; background-color: # FFFF00; margin: 5px; padding: 20px; text-align: center; height: 20px; width: 20px; float: left ;}</style> <script type = "text/javascript"> document. onclick = function () {var I = $ ("div "). size () + 1; // get the number of divs (no div block yet) $ (document. body ). append ($ ("<div>" + I + "</div>"); // Add a div block $ ("# number" ).html (I );} </script> A total of <span id = "numb Er "> 0 </span> DIV blocks. Click to add

2. Extract Elements

In jQuery, if you want to extract an element from a selector, the most direct method is to use square brackets and serial numbers, for example;

$("img[title]")[1]

Obtains the second element of all the img tags with the title attribute set. JQuery also provides the get (index) method to extract elements. The following code is exactly the same as the above Code.

$("img[title]")get(1)

The get method can convert an element into an array of element objects without setting any parameters, as shown in the following example:

<Style> div {border: 1px solid #003a75; background-color: # FFFF00; margin: 5px; padding: 20px; text-align: center; height: 20px; width: 20px; float: left ;}</style> <script type = "text/javascript"> function displayleb (ndiv) {for (var I = 0; I <ndiv. length; I ++) $ (document. body ). append ($ ("<div style = 'background:" + ndiv [I]. style. background + "; '>" + ndiv [I]. innerHTML + "</div>");} $ (function () {var aDiv = $ ("div "). get (); // convert to the div object array displayleb (aDiv. reverse () ;}); </script> <div style = "background: # FFFFFF"> 1 </div> <div style = "background: # CCCCCC "> 2 </div> <div style =" background: #999999 "> 3 </div> <div style =" background: #666666 "> 4 </div> <div style =" background: #333333 "> 5 </div> <div style =" background: #000000 "> 6 </div>

The code above converts the six <div> blocks of the page into an array using the get () method, then returns the array reverse order reverse (), and passes it to the displayleb () function, then, you can add them to the page one by one.

The get (index) method can obtain the elements at the specified position. In turn, the index (element) method can find the position of the element. For example

var iNum=$("li").index($(li[title=isaac]")[0])

Take the <li titile = "isaac"> mark the position of the entire <li> tag list and return the position to the integer iNum. the following is an example of the typical use of the index (element) method.

For example, use the index () method to obtain the sequence number of an element.

<Style> div {border: 1px solid #003a75; background-color: # FFFF00; margin: 5px; padding: 20px; text-align: center; height: 20px; width: 20px; float: left ;}</style> <script type = "text/javascript" >$ (function () {// div click () add and click the function $ ("div "). click (function () {// pass itself through the this keyword to obtain its serial number. Var index = $ ("div "). index (this) + 1; $ ("# display" example .html (index. toString () ;}}); </script> <div style = "background: # FFFFFF"> 1 </div> <div style = "background: # CCCCCC "> 2 </div> <div style =" background: #999999 "> 3 </div> <div style =" background: #666666 "> 4 </div> <div style =" background: #333333 "> 5 </div> <div style =" background: #000000 "> 6 </div> click the <span id =" display "> </span> div.

The code block itself uses the this keyword to pass in the index () method, get its serial number, and use click () to add events to display the serial number.

3. add, delete, and filter elements

In addition to obtaining the selected element, jQuery also provides a series of methods to modify the element set, such as adding an element using the add () method.

$("img[alt]").add("img[title]")

The above code combines the images with alt elements and those with title attributes for unified O & M by other methods. It is equivalent

$("img[alt],img[title]")

For example, you can add css attributes to the element set after the combination.

$("img[alt]").add("img[title]").addClass("altcss")

Opposite to the add () method, the not () method can remove some elements in the element set to form a set.

$("li[title]").not("[title*=isaac]")

The code above indicates that all the tags with the title attribute selected, excluding the <li> with the title value containing "isaac.

Example:

<style>            div {                border: 1px solid #003a75;                background-color: #FFFF00;                margin: 5px;                padding: 20px;                text-align: center;                height: 20px;                width: 20px;                float: left;            }            .altcss {                border: 2px solid #000000;            }        }        </style>        <script type="text/javascript">            $(function() {                $("div").not(".green, #blueone").addClass("altcss");            });        </script>        <div></div>        <div id="blueone"></div>        <div></div>        <div class="green"></div>        <div class="green"></div>        <div class="gray"></div>        <div></div>

The above Jquery removes the <div> block with the style "green" and "blueone" using the not () method, and adds the altcss style to the remaining div block.

The parameters received by the not () method cannot contain specific elements. They can only be passed through common expressions. For example, the following code is incorrect.

$("li[title]").not("img[title*=isaac]")

The correct statement is as follows:

$("li[tile]").not("[title*=isaac]")

In addition to add () and not (), jQuery also provides a more powerful filter () method to filter elements. Filter () can accept two types of parameters. One method, like the not () method, accepts a common expression. The Code is as follows:

$("li").filter("[title*=isaac]")

The code above indicates that the li element combination with the title value containing the isaac string is filtered out.

And

$("li[title*=isaac]")

The filtered combination is the same.

<script type="text/javascript">            $(function() {                $("div").addClass("css1").filter("[class*=middle]").addClass("css2");            });        </script>        <div></div>        <div class="middle"></div>        <div class="middle"></div>        <div class="middle"></div>        <div class="middle"></div>        <div></div>

In the above Code, the four class attributes are middle. Jq adds the css1 style to all div blocks and then uses the filter () method, add the CSS 2 style to the div that contains the middle in the class.

In the filter () parameter, it cannot be equal to or equal to match (=) directly. It can only use the prefix (^ =) or suffix (& = ), or any match (* = ).

Filter () another type of parameter is a function, which is retained for matching the returned ture element; otherwise, the set is excluded. Function parameters are powerful and allow you to customize filter functions.

For example:

<script type="text/javascript">            $(function() {                $("div").addClass("css1").filter(function(index) {                    return index == 1 || $(this).attr("id") == "fourth";                }).addClass("css2");            });        </script>      <div id="first"></div>    <div id="second"></div>    <div id="third"></div>    <div id="fourth"></div>    <div id="fifth"></div>

Run the preceding jq:

Add css1 to all the divs and then use the function returned by filter () to filter the first divs in the list (index is 1). The id is the div element of fourth and add css2.

4. query and filter new element groups

Jq also provides some useful method combinations to obtain new element combinations through queries. For example, the find () method. Filter elements by matching Selector

$("p").find("span")

Indicates a combination of <span> tags found under the <p> tag

Completely equal

$("span",$("p"))
$(function(){    $("p").find("span").addClass("css1");});<p><span>Hello</span>, how are you?</p>

Add a css1 style to Hello.

In addition, you can also use the is () method to check whether a specified element is contained. For example, you can use the following code to check whether the <div> block on the page contains an image.

var himg = $("div").is("img");

Imagine that is () can be used in combination with filter (), Isn't it cool?

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.