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

Native JS implements table sorting

小云云
Release: 2017-12-06 14:52:03
Original
2930 people have browsed it

I have been learning JS table sorting recently, but I didn’t expect that the inconspicuous table sorting actually implies many JS knowledge points. Record this learning process here. Hope it helps everyone too.

Complete table sorting involves the following knowledge points:

  • call method uses

  • sort method in-depth

  • Data Binding

  • DOM Mapping

##The following summarizes these knowledge points in detail, and finally combines these Knowledge points implement the following table sorting case.


Native JS implements table sorting

Complete case source code: https://github.com/daweihe/JS...

1. Summary of knowledge points

1. Use of the call method

The function of the call method is to change the this pointer in the method.

call This method is defined in

Function.prototype. Any function we define can be considered as an instance of the Function class. Then you can find the prototype of the class through the __proto__ attribute of the instance. Any function can call methods such as call and apply.

Let’s look at an example first:

var obj = {
    name : 'JS'
}

function testCall () {
    console.log(this);
}

testCall.call( obj );     // {name: "JS"}
Copy after login
First function

testCall finds the call method to execute through the prototype chain search mechanism. The call method calls the call method during the execution process. This in the instance is changed to the first parameter of call, and then the instance function of the call method is called and executed.

Look at two questions:

function fn1() {
    console.log(1);
    console.log(this);
}

function fn2() {
    console.log(2);
    console.log(this);
}

fn1.call(fn2);   //this -> fn2
fn1.call.call(fn2);   //这里的call是改变function.__proto__.call的call方法中的this,相当于执行参数
Copy after login
When the call method is executed, the first parameter of the call method is used to change this, and starting from the second parameter is passed to The parameters of the function calling call.

In non-strict mode, if no parameters are passed to the call method, or null or undefined is passed, this will point to

window.

sum.call(); //window
sum.call(null); //window
sum.call(undefined); //window
Copy after login
Copy after login
The execution of call in strict mode is different from that in non-strict mode:

sum.call(); //undefined
sum.call(null); //null
sum.call(undefined); //undefined
Copy after login
Copy after login
The following uses the call method to implement a method of converting an array-like array into an array:

function listToArray (likeAry) {
    var ary = [];
    try {
        ary = Array.prototype.slice.call(likeAry);
    } catch (e) {
        for (var i = 0; i < likeAry.length; i ++) {
            ary[ary.length] = likeAry[i];
        }
    }
    return ary;
}
Copy after login
Copy after login

and call Similar methods include the apply and bind methods, which are briefly summarized here.

The apply method has the same function as the call method, except that the form of passing parameters is different. apply wraps the parameters of the function in an array:

function sum(num1, num2) {
    console.log(num2 + num1);
    console.log(this);
}

sum.apply(null,[100,200]);
Copy after login
Copy after login

The bind method is also used to change this key Literal, but it only changes the point of this and does not immediately execute the function that calls this.

function sum(num1, num2) {
    console.log(num2 + num1);
    console.log(this);
}

var obj = {name : &#39;zx&#39;}

var temp = sum.bind(obj);   //temp已经是被改变了this的函数
temp(100,200);              //当我们需要的时候才执行


//或者像这样处理
var temp = sum.bind(null, 100, 200);
temp();
Copy after login
Copy after login

The bind method embodies the preprocessing idea in js.

2. In-depth sorting

We know that the

sort method of an array can only sort arrays within 10. If there are numbers greater than 10 in the array that needs to be sorted, we need to pass the callback function to the sort method. The common one is like this:

ary.sort(function (a,b) {
    return a - b;
});
Copy after login
Copy after login

This way, the array can be sorted in ascending order. . So what is the principle behind this sorting?

For the two parameters passed in:

a represents the current item in the found array, and b represents the item after the current item.

  • return a -b: If a is greater than b, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is ascending order

  • return b -a: If b is greater than a, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is descending order

After understanding the basic principles, how to sort such a two-dimensional array by age?

var persons = [{
    name:&#39;dawei&#39;,
    age:55
},{
    name:&#39;ahung&#39;,
    age:3
},{
    name:&#39;maomi&#39;,
    age:2
},{
    name:&#39;heizi&#39;,
    age:78
},{
    name:&#39;afu&#39;,
    age:32
}];
Copy after login
Copy after login

It’s actually very simple:

ary.sort(function(a,b){
    return a.age - b.age;
});
Copy after login
Copy after login

If you sort by name, the

localeCompare() method of the string is involved:

ary.sort(function(a,b){
    return a.name.localeCompare(b.name);
});
Copy after login
Copy after login

name.localeCompare()This method will compare the letters of the two strings. If the first letter of the previous string appears in a position higher than the first character of the latter string among the 24 English letters, If it appears in the front position, the first string is considered small and -1 is returned. If it appears later, the first string is considered larger and 1 is returned. If the compared characters are equal. Then compare the next character.

This method is very practical and is often used to sort by surname. For Chinese characters, this method will automatically convert the Chinese characters into Chinese Pinyin for comparison.

3. Data binding

In js, dynamic binding or string splicing is generally used to implement data binding.

Dynamic binding:

//ary为需要添加到页面中的数据数组
var op = document.getElementById("box");//获取容器
var myUl = op.getElementsByTagName("ul")[0];//获取列表

var arrLength = ary.length;
for (var i = 0;i < arrLength ; i ++)
{  //动态创建元素
    var oli = document.createElement("li");
    oli.innerHTML = &#39;<span>' + (i + 5) + '</span>' + ary[i].title;
    myUl.appendChild(oli);//动态添加元素
}
Copy after login
Copy after login
Every addition will cause a DOM reflow. If the amount of data is too large, this will seriously affect performance.

Regarding DOM reflow and redrawing, I recommend you read this article: http://www.css88.com/archives...

Splicing strings:

var str = "";
for(var i=0; i<ary.length; i++){
    str += &#39;<li>';
    str += '<span>';
    str += (i+5);
    str += '</span>';
    str += ary[i].title;
    str += '</li>';
}

myUl.innerHTML += str;
Copy after login
Copy after login
Although this method only causes one reflow, it will remove all events and attributes from the original elements. If we add an event for the li tag in the list when the mouse moves in and the background changes color, this method will invalidate this event.

In order to solve the problems caused by the above two data binding methods, we use document fragments to add data.

var frg = document.createDocumentFragment();//创建文档碎片
for (var i =0; i <ary.length ;i ++ ){
    var li = document.createElement("li");
    li.innerHTML = '<span>' + ( i + 5 ) + '</span>' + ary[i].title;
    frg.appendChild(li);//将数据动态添加至文档碎片中
}
myUl.appendChild(frg); //将数据一次性添加到页面中
frg = null;  //释放内存
Copy after login
Copy after login
This will only cause DOM reflow once and retain the original existing events.

4、DOM映射

DOM映射机制:所谓映射,就是指两个元素集之间元素相互“对应”的关系。页面中的标签集合和在JS中获取到的元素对象(元素集合)就是这样的关系。如果页面中的HTML标签结构发送变化,那么集合中对应的内容也会跟着自动改变。

<ul id="myul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
Copy after login
Copy after login

对于这样一个列表使用下列脚本:

var myul = document.getElementById("myul");
var mylis = myul.getElementsByTagName('li');
    for (var i = mylis.length - 1 ; i >= 0; i --) {
        myul.appendChild(mylis[i]);
    }
console.log(mylis.length);   // 5
Copy after login
Copy after login

将获取到的列表元素反序重新插入ul中,那么ul列表会变成下面这样:

<ul id="myul">
    <li>5</li>
    <li>4</li>
    <li>3</li>
    <li>2</li>
    <li>1</li>
</ul>
Copy after login
Copy after login

我们看到列表的长度依然是5,只是位置颠倒了。这是因为每个li标签和JS中获取的标签对象存在一个对应关系,当某个标签被重新插入到页面中时,页面中对应的标签会移动到插入的位置。这就是DOM映射。

二、实现表格排序

1、使用ajax获取数据

之所以使用动态获取数据,是为了使用文档碎片绑定数据。

var res = ''; //声明一个全局变量,接收数据
var xhr = new XMLHttpRequest();
xhr.open('get', 'date.txt', false);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        res = JSON.parse(xhr.responseText);
    }
}
xhr.send(null);
Copy after login
Copy after login

此时数据就保存在了res这个全局变量之中。

2、使用文档碎片绑定数据

var frg = document.createDocumentFragment();
for (let i = 0; i < res.length; i++) {
    var tr = document.createElement("tr");
    for (key in res[i]) {
        var td = document.createElement("td");
        td.innerHTML = res[i][key];
        tr.appendChild(td);
    }
    frg.appendChild(tr);
}
tbody.appendChild(frg);
Copy after login

3、对表格进行排序

这里涉及的点较多

//为两列添加点击事件
for (let i = 0; i < ths.length; i++) {
    let curTh = ths[i];
    curTh.sortFlag = -1; //用于对列进行升降序排列
    curTh.index = i; //记录当前点击列的索引,便于排序操作
    if (curTh.className == &#39;sort&#39;) {
        curTh.onclick = function() {
            sort.call(this); //改变排序函数内this的指向,让其指向当前点击列
        }
    }
}


//排序方法
function sort() {
    //对数组元素进行排序
    let target = this; //这里将this取出,因为在sort方法里需要使用该this,但是sort方法里的this是调用方法的数组
    this.sortFlag *= -1; //1 代表升序   -1代表降序
    let ary = listToArray(bodyTrs); //获取body数据
    ary = ary.sort(function(a, b) {
        let one = a.cells[target.index].innerHTML;
        let two = b.cells[target.index].innerHTML;
        let oneNum = parseFloat(one);
        let twoNum = parseFloat(two);

        if (isNaN(oneNum) || isNaN(two)) {
            return one.localeCompare(two) * target.sortFlag;
        } else {
            return (oneNum - twoNum) * target.sortFlag;
        }
    });
    //把排好序的数组重新写入页面
    let frg = document.createDocumentFragment();
    for (let i = 0; i < ary.length; i++) {
        rg.appendChild(ary[i]);
    }
    tbody.appendChild(frg);
    frg = null;

    //点击某列时,要将其他列的排序标志恢复为-1,让下次再点击任意一个标签时都是默认是升序排列
    for (let i = 0; i < ths.length; i++) {
        if (ths[i] != this) {
            ths[i].sortFlag = -1;
        }
    }
}
Copy after login

表格排序应用很常见,在面试中也会有这样的题目。这个小案例做下来,受益匪浅。这是我在学习的某峰学院的JS课程中的一个案例,如果对JS掌握不扎实的同学,欢迎保存:链接: https://pan.baidu.com/s/1jHVy8Uq 密码: v4jk。如果链接失效,加Q群领取:154658901


I have been learning JS table sorting recently, but I didn’t expect that the inconspicuous table sorting actually implies many JS knowledge points. Record this learning process here. Hope it helps everyone too.

Complete table sorting involves the following knowledge points:

  • call method uses

  • sort method in-depth

  • Data Binding

  • DOM Mapping

##The following summarizes these knowledge points in detail, and finally combines these Knowledge points implement the following table sorting case.


Native JS implements table sorting

Complete case source code: https://github.com/daweihe/JS...

1. Summary of knowledge points

1. Use of the call method

The function of the call method is to change the this pointer in the method.

call This method is defined in

Function.prototype. Any function we define can be considered as an instance of the Function class. Then you can find the prototype of the class through the __proto__ attribute of the instance. Any function can call methods such as call and apply.

Let’s look at an example first:

var obj = {
    name : &#39;JS&#39;
}

function testCall () {
    console.log(this);
}

testCall.call( obj );     // {name: "JS"}
Copy after login

First function

testCall finds the call method to execute through the prototype chain search mechanism. The call method calls the call method during the execution process. This in the instance is changed to the first parameter of call, and then the instance function of the call method is called and executed.

Look at two questions:

function fn1() {
    console.log(1);
    console.log(this);
}

function fn2() {
    console.log(2);
    console.log(this);
}

fn1.call(fn2);   //this -> fn2
fn1.call.call(fn2);   //这里的call是改变function.__proto__.call的call方法中的this,相当于执行参数
Copy after login
When the call method is executed, the first parameter of the call method is used to change this, and starting from the second parameter is passed to The parameters of the function calling call.

In non-strict mode, if no parameters are passed to the call method, or null or undefined is passed, this will point to

window.

sum.call(); //window
sum.call(null); //window
sum.call(undefined); //window
Copy after login
Copy after login
The execution of call in strict mode is different from that in non-strict mode:

sum.call(); //undefined
sum.call(null); //null
sum.call(undefined); //undefined
Copy after login
Copy after login
The following uses the call method to implement a method of converting an array-like array into an array:

function listToArray (likeAry) {
    var ary = [];
    try {
        ary = Array.prototype.slice.call(likeAry);
    } catch (e) {
        for (var i = 0; i < likeAry.length; i ++) {
            ary[ary.length] = likeAry[i];
        }
    }
    return ary;
}
Copy after login
Copy after login

and call Similar methods include the apply and bind methods, which are briefly summarized here.

The apply method has the same function as the call method, except that the form of passing parameters is different. apply wraps the parameters of the function in an array:

function sum(num1, num2) {
    console.log(num2 + num1);
    console.log(this);
}

sum.apply(null,[100,200]);
Copy after login
Copy after login

The bind method is also used to change this key Literal, but it only changes the point of this and does not immediately execute the function that calls this.

function sum(num1, num2) {
    console.log(num2 + num1);
    console.log(this);
}

var obj = {name : &#39;zx&#39;}

var temp = sum.bind(obj);   //temp已经是被改变了this的函数
temp(100,200);              //当我们需要的时候才执行


//或者像这样处理
var temp = sum.bind(null, 100, 200);
temp();
Copy after login
Copy after login

The bind method embodies the preprocessing idea in js.

2. In-depth sorting

We know that the

sort method of an array can only sort arrays within 10. If there are numbers greater than 10 in the array that needs to be sorted, we need to pass the callback function to the sort method. The common one is like this:

ary.sort(function (a,b) {
    return a - b;
});
Copy after login
Copy after login

This way, the array can be sorted in ascending order. . So what is the principle behind this sorting?

For the two parameters passed in:

a represents the current item in the found array, and b represents the item after the current item.

  • return a -b: If a is greater than b, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is ascending order

  • return b -a: If b is greater than a, return the result, and a and b exchange positions. If a is smaller than b, then the positions of a and b remain unchanged. This is descending order

After understanding the basic principles, how to sort such a two-dimensional array by age?

var persons = [{
    name:&#39;dawei&#39;,
    age:55
},{
    name:&#39;ahung&#39;,
    age:3
},{
    name:&#39;maomi&#39;,
    age:2
},{
    name:&#39;heizi&#39;,
    age:78
},{
    name:&#39;afu&#39;,
    age:32
}];
Copy after login
Copy after login

It’s actually very simple:

ary.sort(function(a,b){
    return a.age - b.age;
});
Copy after login
Copy after login

If you sort by name, the

localeCompare() method of the string is involved:

ary.sort(function(a,b){
    return a.name.localeCompare(b.name);
});
Copy after login
Copy after login

name.localeCompare()This method will compare the letters of the two strings. If the first letter of the previous string appears in a position higher than the first character of the latter string among the 24 English letters, If it appears in the front position, the first string is considered small and -1 is returned. If it appears later, the first string is considered larger and 1 is returned. If the compared characters are equal. Then compare the next character.

This method is very practical and is often used to sort by surname. For Chinese characters, this method will automatically convert the Chinese characters into Chinese Pinyin for comparison.

3. Data binding

In js, dynamic binding or string splicing is generally used to implement data binding.

Dynamic binding:

//ary为需要添加到页面中的数据数组
var op = document.getElementById("box");//获取容器
var myUl = op.getElementsByTagName("ul")[0];//获取列表

var arrLength = ary.length;
for (var i = 0;i < arrLength ; i ++)
{  //动态创建元素
    var oli = document.createElement("li");
    oli.innerHTML = &#39;<span>' + (i + 5) + '</span>' + ary[i].title;
    myUl.appendChild(oli);//动态添加元素
}
Copy after login
Copy after login
Every addition will cause a DOM reflow. If the amount of data is too large, this will seriously affect performance.

Regarding DOM reflow and redrawing, I recommend you read this article: http://www.css88.com/archives...

Splicing strings:

var str = "";
for(var i=0; i<ary.length; i++){
    str += &#39;<li>';
    str += '<span>';
    str += (i+5);
    str += '</span>';
    str += ary[i].title;
    str += '</li>';
}

myUl.innerHTML += str;
Copy after login
Copy after login
Although this method only causes one reflow, it will remove all events and attributes from the original elements. If we add an event for the li tag in the list when the mouse moves in and the background changes color, this method will invalidate this event.

In order to solve the problems caused by the above two data binding methods, we use document fragments to add data.

var frg = document.createDocumentFragment();//创建文档碎片
for (var i =0; i <ary.length ;i ++ ){
    var li = document.createElement("li");
    li.innerHTML = '<span>' + ( i + 5 ) + '</span>' + ary[i].title;
    frg.appendChild(li);//将数据动态添加至文档碎片中
}
myUl.appendChild(frg); //将数据一次性添加到页面中
frg = null;  //释放内存
Copy after login
Copy after login
This will only cause DOM reflow once and retain the original existing events.

4、DOM映射

DOM映射机制:所谓映射,就是指两个元素集之间元素相互“对应”的关系。页面中的标签集合和在JS中获取到的元素对象(元素集合)就是这样的关系。如果页面中的HTML标签结构发送变化,那么集合中对应的内容也会跟着自动改变。

<ul id="myul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
Copy after login
Copy after login

对于这样一个列表使用下列脚本:

var myul = document.getElementById("myul");
var mylis = myul.getElementsByTagName('li');
    for (var i = mylis.length - 1 ; i >= 0; i --) {
        myul.appendChild(mylis[i]);
    }
console.log(mylis.length);   // 5
Copy after login
Copy after login

将获取到的列表元素反序重新插入ul中,那么ul列表会变成下面这样:

<ul id="myul">
    <li>5</li>
    <li>4</li>
    <li>3</li>
    <li>2</li>
    <li>1</li>
</ul>
Copy after login
Copy after login

我们看到列表的长度依然是5,只是位置颠倒了。这是因为每个li标签和JS中获取的标签对象存在一个对应关系,当某个标签被重新插入到页面中时,页面中对应的标签会移动到插入的位置。这就是DOM映射。

二、实现表格排序

1、使用ajax获取数据

之所以使用动态获取数据,是为了使用文档碎片绑定数据。

var res = ''; //声明一个全局变量,接收数据
var xhr = new XMLHttpRequest();
xhr.open('get', 'date.txt', false);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        res = JSON.parse(xhr.responseText);
    }
}
xhr.send(null);
Copy after login
Copy after login

此时数据就保存在了res这个全局变量之中。

2、使用文档碎片绑定数据

var frg = document.createDocumentFragment();
for (let i = 0; i < res.length; i++) {
    var tr = document.createElement("tr");
    for (key in res[i]) {
        var td = document.createElement("td");
        td.innerHTML = res[i][key];
        tr.appendChild(td);
    }
    frg.appendChild(tr);
}
tbody.appendChild(frg);
Copy after login

3、对表格进行排序

这里涉及的点较多

//为两列添加点击事件
for (let i = 0; i < ths.length; i++) {
    let curTh = ths[i];
    curTh.sortFlag = -1; //用于对列进行升降序排列
    curTh.index = i; //记录当前点击列的索引,便于排序操作
    if (curTh.className == 'sort') {
        curTh.onclick = function() {
            sort.call(this); //改变排序函数内this的指向,让其指向当前点击列
        }
    }
}


//排序方法
function sort() {
    //对数组元素进行排序
    let target = this; //这里将this取出,因为在sort方法里需要使用该this,但是sort方法里的this是调用方法的数组
    this.sortFlag *= -1; //1 代表升序   -1代表降序
    let ary = listToArray(bodyTrs); //获取body数据
    ary = ary.sort(function(a, b) {
        let one = a.cells[target.index].innerHTML;
        let two = b.cells[target.index].innerHTML;
        let oneNum = parseFloat(one);
        let twoNum = parseFloat(two);

        if (isNaN(oneNum) || isNaN(two)) {
            return one.localeCompare(two) * target.sortFlag;
        } else {
            return (oneNum - twoNum) * target.sortFlag;
        }
    });
    //把排好序的数组重新写入页面
    let frg = document.createDocumentFragment();
    for (let i = 0; i < ary.length; i++) {
        rg.appendChild(ary[i]);
    }
    tbody.appendChild(frg);
    frg = null;

    //点击某列时,要将其他列的排序标志恢复为-1,让下次再点击任意一个标签时都是默认是升序排列
    for (let i = 0; i < ths.length; i++) {
        if (ths[i] != this) {
            ths[i].sortFlag = -1;
        }
    }
}
Copy after login

以上内容就是原生JS实现表格排序,希望能帮助到大家。

js学习总结经典小案例之表格排序

jquery中tablesorter表格排序组件是如何使用的?

js表格排序实例详解(支持int,float,date,string四种数据类型)

The above is the detailed content of Native JS implements table sorting. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!