Home Web Front-end JS Tutorial Using jQuery to sort an unordered list

Using jQuery to sort an unordered list

Apr 01, 2017 am 09:23 AM

The example in this article describes how jQuery implements the sorting function of unordered lists. Share it with everyone for your reference, the details are as follows:

The principle of using jQuery to sort the unordered list is: get all the list items in the unordered list and convert them into array form, Use JavaScriptFunction Sort it and output it again. The jQuery functions used include ready(), get(),

text(), each(), append() and JavaScript function sort().

1. jQuery function introduction
(1)jQuery function get()--get the set of matching elements
This function obtains all matching elements in a backward-compatible way (different from jQueryobject, actually an array of elements). Its syntax is as follows:
object.get()

Note: This function is very useful if you want to directly operate DOM objects instead of jQuery objects.

(2) jQuery function text()--Getting and setting element content

This function gets and sets the text content of matching elements. The syntax is as follows:

object.text([val|fn])

Note: The val and fn parameters are optional. val is to set the text content value of the element; the fn(index, text) function returns a string , accepting two parameters, index is the index position of the element in the collection, and text is The original text value.

(3) jQuery function append()--Append content to elements

This function appends content to each matching element. The syntax is as follows:

object.append(content|fn)

Note: This operation is similar to executing the appendChild method on specified elements and adding them to the document. The content parameter represents the appended content; fn(index,html) returns an HTML string for appending to each matching element. It accepts two parameters. The index parameter is the index value of the object in this collection, and the html parameter is this The original html value of the object.

2. JavaScript function introduction

JavaScript function sort()--element sorting, used to sort array elements. The syntax is as follows:

arrayObject.sort([sortby])

Note: sortby is optional, specifies the sorting order, and must be a function. The return value is the sorted array itself. If this method is called without arguments, the elements in the array will be sorted alphabetically. To be more precise, it is sorted according to the order of character encoding. To achieve this, the elements of the array should first be converted to strings (if necessary) for comparison.

If you want to sort by other criteria, you need to provide a comparison function, which compares two values ​​and returns a number that describes the relative order of the two values. The comparison function should have two parameters a and b, and its return value is as follows: if a is less than b, a should appear before b in the sorted array, then a value less than 0 is returned. If a equals b, then 0 is returned. If a is greater than b, a value greater than 0 is returned.

3. Functional implementation

The steps to implement the unordered list item sorting function are as follows.

(1) Get all list items and load them into an array.

(2) Sort array objects.

(3) Repopulate the sorted array into the unordered list.

First, introduce the jQuery library:

<script language="JavaScript" src="jquery-1.7.2.min.js"></script>
Copy after login

Then, add the following sorting function code:

<script language="JavaScript" type="text/JavaScript">
 $(document).ready(function(){
  var items = $(".orderobj li").get(); //获取所有待排序li装入数组items
  items.sort(function(a,b) //调用JavaScript内置函数sort
  {
    var elementone = $(a).text();
    var elementtwo = $(b).text();
    if(elementone < elementtwo) return -1;
    if(elementone > elementtwo) return 1;
   return 0;
 });
 var ul = $(".orderobj");
 $.each(items,function(i,li)
 //通过遍历每一个数组元素,填充无序列表
 {
   ul.append(li);
 });
 });
</script>
Copy after login

The above code is sorted by the array And repopulate the unordered list so that the list items are in order. The specific effect is as shown in the figure:

Using jQuery to sort an unordered list

The above is the detailed content of Using jQuery to sort an unordered list. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to sort WPS scores How to sort WPS scores Mar 20, 2024 am 11:28 AM

In our work, we often use wps software. There are many ways to process data in wps software, and the functions are also very powerful. We often use functions to find averages, summaries, etc. It can be said that as long as The methods that can be used for statistical data have been prepared for everyone in the WPS software library. Below we will introduce the steps of how to sort the scores in WPS. After reading this, you can learn from the experience. 1. First open the table that needs to be ranked. As shown below. 2. Then enter the formula =rank(B2, B2: B5, 0), and be sure to enter 0. As shown below. 3. After entering the formula, press the F4 key on the computer keyboard. This step is to change the relative reference into an absolute reference.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to sort WPS tables to facilitate data statistics How to sort WPS tables to facilitate data statistics Mar 20, 2024 pm 04:31 PM

WPS is a very complete office software, including text editing, data tables, PPT presentations, PDF formats, flow charts and other functions. Among them, the ones we use most are text, tables, and demonstrations, and they are also the ones we are most familiar with. In our study work, we sometimes use WPS tables to make some data statistics. For example, the school will count the scores of each student. If we have to manually sort the scores of so many students, it will be really a headache. In fact, we don’t have to worry, because our WPS table has a sorting function to solve this problem for us. Next, let’s learn how to sort WPS together. Method steps: Step 1: First we need to open the WPS table that needs to be sorted

How to reorder multiple columns in Power Query via drag and drop How to reorder multiple columns in Power Query via drag and drop Mar 14, 2024 am 10:55 AM

In this article, we will show you how to reorder multiple columns in PowerQuery by dragging and dropping. Often, when importing data from various sources, columns may not be in the desired order. Reordering columns not only allows you to arrange them in a logical order that suits your analysis or reporting needs, it also improves the readability of your data and speeds up tasks such as filtering, sorting, and performing calculations. How to rearrange multiple columns in Excel? There are many ways to rearrange columns in Excel. You can simply select the column header and drag it to the desired location. However, this approach can become cumbersome when dealing with large tables with many columns. To rearrange columns more efficiently, you can use the enhanced query editor. Enhancing the query

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

How to sort in excel How to sort in excel Mar 05, 2024 pm 04:12 PM

Sorting methods in excel: 1. Single column sorting; 2. Multiple column sorting; 3. Custom sorting. Detailed introduction: 1. Single-column sorting is the most common sorting method. It sorts according to a selected column; 2. Multi-column sorting refers to sorting data in multiple columns, usually sorting according to a certain column first. On the basis of, sort by another column; 3. Custom sorting, allowing users to define the sort order according to their own needs.

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles