jquery traversal of various uses

Source: Internet
Author: User
Tags json

Here is a function (omitting the code before and after) to implement the table row stripe effect:
The code is as follows:

The code is as follows Copy Code
function stripe () {
$ (' #news '). Find (' Tr.alt '). Removeclass (' Alt ');
$ (' #news tbody '). each (function () {
$ (this). Children (': visible '). has (' TD ')
. Filter (': Group (3) '). addclass (' Alt ');
});
}

The stripe () function two times uses the ID selector #news the lookup element: one to remove the class from the row with the Alt class, and the other to add the class to the newly selected row.

There are two ways to optimize this function, one is consonant.

Consonant
Consonant optimizes the use of the internal object stack and the. End () method of jquery. The optimized code is as follows:
The code is as follows:

The code is as follows Copy Code
function stripe () {
$ (' #news ').
Find (' Tr.alt '). Removeclass (' Alt '). End ()
Find (' tbody '). each (function () {
$ (this). Children (': visible '). has (' TD ')
. Filter (': Group (3) '). addclass (' Alt ');
});
}

The first call. Find () pushes the table rows onto the stack, and then the. End () method pops the rows up so that the next call is made. Find () is still performing an operation on the #news table. This reduces the two-time selector lookup to one time.

Another optimization method is caching.

Cache
The so-called cache, here is to save the results of the previous operation for future reuse. The optimized code is as follows:
The code is as follows:

The code is as follows Copy Code
var $news = $ (' #news ');
function stripe () {
$news. Find (' Tr.alt '). Removeclass (' Alt ');
$news. Find (' tbody '). each (function () {
$ (this). Children (': visible '). has (' TD ')
. Filter (': Group (3) '). addclass (' Alt ');
});
}

The caching approach is a bit verbose compared to the consonant method, as an extra variable is created to hold the jquery object. But from another perspective, this approach can completely separate the two operations of the selected element in the code, which may satisfy our other needs. Similarly, because the selected element can be saved outside the stripe () function, it avoids the repeated query selector every time the function is invoked

The code is as follows Copy Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language= "javascript" type= "Text/javascript" src= "Jquery.min.js" ></script>
<script type= "Text/javascript" >
$ (function () {

var tbody = "";
------------traverse the object. Use of each-------------
Object syntax JSON data format (when the server-side callback returns the object data format is JSON data format, you must ensure that the JSON format requirements, the callback object must use the Eval function to transform (otherwise it will not get object). This article does not provide a detailed description of the server-side callback data problem, we will directly customize the object.
var obj =[{"name": "Navy", "Password": "123456"}];
$ ("#result"). HTML ("------------traversal object. Each use-------------");
alert (obj);//is an OBJECT element
Use each to traverse the following
$.each (Obj,function (n,value) {
Alert (n+ ' +value);
var trs = "";
TRS + + "<tr><td>" + value.name + "</td> <td>" + Value.password + "</td></tr>";
Tbody + = TRS;
});

$ ("#project"). Append (tbody);

});
</script>
</HEAD>

<BODY>
<div id= "Result" style= "font-size:16px;color:red;" ></div>
<table cellpadding=5 cellspacing=1 width=620 id= "Project" border= "1" >
<tr>
<th> User name </th>
<th> Password </th>
</tr>
</table>
</BODY>
</HTML>


2.jQuery Traversal Array

The code is as follows Copy Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en"
    < title> New Document </title>
  <script language= "javascript" type= "Text/javascript" src= " Jquery.min.js "></script>
  <script  type=" Text/javascript "
      $ (function () {

       var tbody = "";
   
    //------------traverse the array. Each use-------------
            var anarray = [' One ', ' two ', ' three '];
     $ ("#result"). HTML ("------------traversal array. Each use-------------");
           $.each (anarray,function (n,value) {
           
             alert (n+ ' +value);
           var trs = "";
             TRS + = "<tr><td>" +value+ "</td></tr>";
              tbody + = TRS;
           });

$ ("#project"). Append (tbody);

});
</script>
</HEAD>

<BODY>
------------the body part of this section with 1--------------------

</BODY>
</HTML>


3.jQuery Traversal List collection (in fact, not much different from traversing an object, but the format of the problem

The code is as follows Copy Code

) <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language= "javascript" type= "Text/javascript" src= "Jquery.min.js" ></script>
<script type= "Text/javascript" >
$ (function () {

var tbody = "";

------------traverse the list collection. Use-------------for each
var obj =[{"name": "Navy", "Password": "123456"},{"name": "Kobe", "Password": "333333"}];
$ ("#result"). HTML ("traverse the list collection. Each's use");
alert (obj);//is an OBJECT element
Use each to traverse the following
$.each (Obj,function (n,value) {
Alert (n+ ' +value);
var trs = "";
TRS + + "<tr><td>" +value.name+ "</td> <td>" + Value.password + "</td></tr>";
Tbody + = TRS;
});
$ ("#project"). Append (tbody);

});
</script>
</HEAD>

<BODY>
------------the body part of this section with 1--------------------

</BODY>
</HTML>

The JQuery traversal function includes methods for filtering, locating, and concatenating elements.

function Description
. Add () Adds an element to the collection of matching elements.
. Andself () Adds the set of elements before the stack to the current collection.
. Children () Gets all the child elements of each element in the matching element collection.
. Closest () Starts with the element itself, recursively matches the ancestor element, and returns the first matching ancestral element.
. Contents () Gets the child elements of each element in the matching element collection, including text and annotation nodes.
. each () Iterate over the JQuery object, executing the function for each matching element.
. End () Ends the most recent filter operation in the current chain and returns a collection of matching elements back to the previous state.
. EQ () Reduces the collection of matching elements to the new element at the specified index.
. Filter () Reduces the collection of matching elements to a new element that matches the return value of a selector or matching function.
. Find () Gets the descendants of each element in the current matching element collection, filtered by the selector.
. A () Reduces the collection of matching elements to the first element in the collection.
. has () Reduces the collection of matching elements to a collection of descendants that contain specific elements.
. is () Checks the collection of current matching elements according to the selector, and returns True if there is at least one matching element.
. Last () Reduces the collection of matching elements to the last element in the collection.
. Map () Passes each element in the current matching collection to a function, generating a new JQuery object that contains the returned value.
. Next () Gets the sibling elements that are adjacent to each element in the matching element collection.
. Nextall () Gets all sibling elements after each element in the collection of elements, which is filtered by the selector (optional).
. Nextuntil () Gets all sibling elements after each element until the element that matches the selector is encountered.
. Not () Deletes an element from the collection of matching elements.
. offsetparent () Gets the first parent element to use for positioning.
. Parent () Gets the parent element of each element in the current matching element collection, optionally filtered by the selector.
. Parents () Gets the ancestor element of each element in the current matching element collection, optionally filtered by the selector.
. Parentsuntil () Gets the ancestor element of each element in the current matching element collection until the element that matches the selector is encountered.
. Prev () Gets the first sibling element next to each element in the matching element collection, filtered by selector (optional).
. Prevall () Gets all sibling elements before each element in the matching element collection, which is filtered by the selector (optional).
. Prevuntil () Gets all the sibling elements before each element until the element that matches the selector is encountered.
. Siblings () Gets the sibling element of all elements in the matching element collection, which is filtered by the selector (optional).
. Slice () Reduces the set of matching elements to a subset of the specified range.

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.