javascript - 当用户单击列时对表格进行排序

标签 javascript html

我有一个 html 表,它填充了来自 json 的动态值(用 javascript 代码编写)。 当用户单击表格中的任何列标题时,表格应相应地排序。任何建议都会有所帮助。

当用户单击该列时,如果用户第二次单击同一列,表格应升序排序,然后降序排序。

演示 https://jsfiddle.net/o2ram4tu/

示例代码如下:

function CreateTableFromJSON() {
        var myBooks = [
            {
                "Book ID": "1",
                "Book Name": "Computer Architecture",
                "Category": "Computers",
                "Price": "125.60"
            },
            {
                "Book ID": "2",
                "Book Name": "Asp.Net 4 Blue Book",
                "Category": "Programming",
                "Price": "56.00"
            },
            {
                "Book ID": "3",
                "Book Name": "Popular Science",
                "Category": "Science",
                "Price": "210.40"
            }
        ]

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }
        var table = document.getElementById("resulttable");
 var tr = table.insertRow(1);   

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        th, td, p, input {
            font:14px Verdana;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body onload="CreateTableFromJSON()" > 
<table class="fdt-datatable" id="resulttable" name="resulttable">
            <tbody>
            <tr>
                <th name = "bookID"> Book ID</th>
                <th name = "bookName"> Book Name</th>
                <th name = "category"> Category</th>
                <th name = "price"> Price</th>
                </tr>
                </tbody>
                </table>
    <p id="showData"></p>
</body>
 
</html>

最佳答案

我编辑了你的代码并添加了一些新员工堡垒分类
这是 jsfiddle
片段如下

function CreateTableFromJSON() {
        var myBooks = [
            {
                "Book ID": "1",
                "Book Name": "Computer Architecture",
                "Category": "Computers",
                "Price": "125.60"
            },
            {
                "Book ID": "2",
                "Book Name": "Asp.Net 4 Blue Book",
                "Category": "Programming",
                "Price": "56.00"
            },
            {
                "Book ID": "3",
                "Book Name": "Popular Science",
                "Category": "Science",
                "Price": "210.40"
            }
        ]

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }
        var table = document.getElementById("resulttable");
        var tbody = document.getElementById("resulttable_body");
        var tr = tbody.insertRow(0);   

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < myBooks.length; i++) {

            tr = tbody.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }

	
// FOR TABLE SORT
$(document).ready(function(){

var sortOrder = 1; // flag to toggle the sorting order
function getVal(elm, colIndex){
	var td = $(elm).children('td').eq(colIndex).text();
	if(typeof td !== "undefined"){
		var v = td.toUpperCase();
		if($.isNumeric(v)){
			v = parseInt(v,10);
		}
		return v;
	}
}

$(document).on('click', '.sortable', function(){
	var self = $(this);
	var colIndex = self.prevAll().length;
	var o = (sortOrder == 1) ? 'asc' : 'desc'; // you can use for css to show sort direction
	sortOrder *= -1; // toggle the sorting order
	
    $('.sortable').removeClass('asc').removeClass('desc');
    self.addClass(o);

	var tbody = self.closest("table").find("tbody");
	var tr = tbody.children("tr"); //.get();

    tr.sort(function(a, b) {
        var A = getVal(a, colIndex);
        var B = getVal(b, colIndex);

        if(A < B) {
            return -1*sortOrder;
        }
        if(A > B) {
            return 1*sortOrder;
        }
        return 0;
    });

    $.each(tr, function(index, row) {
		//console.dir(row)
        tbody.append(row);
    });

});

});
        th, td, p, input {
            font:14px Verdana;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <title>Convert JSON Data to HTML Table</title>
</head>
<body onload="CreateTableFromJSON()" > 
<table class="fdt-datatable" id="resulttable" name="resulttable">
<thead>
	<tr>
	<th name = "bookID" class="sortable"> Book ID</th>
	<th name = "bookName" class="sortable"> Book Name</th>
	<th name = "category" class="sortable"> Category</th>
	<th name = "price" class="sortable"> Price</th>
	</tr>
</thead>
<tbody id="resulttable_body">
</tbody>
</table>
<p id="showData"></p>
</body>
 
</html>

关于javascript - 当用户单击列时对表格进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56134551/

相关文章:

javascript - 我可以在进度条中显示 $timeout 值吗?

php - 编码时为什么要格式化以及如何格式化

html - 将下拉菜单与容器的 100% 宽度居中对齐

javascript - 防止 VueJS 中的滚动

javascript - 在 iframe 内定位 HTML(需要在提交时重定向 nVite 表单)

javascript - 显示放大弹出窗口时隐藏导航内容

javascript - 如何在父元素缩放时限制子元素倾斜

html - 有条件地更改 Angular 组件的 CSS

javascript - requestAnimFrame 在 Chrome 中为 60FPS,在 FF 中为 1FPS

css - 在父 div 中 float 2 个 div,并将这些 div 一个放在另一个下面