用户单击列

时间:2019-05-14 16:08:37

标签: 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>

2 个答案:

答案 0 :(得分:1)

我编辑了您的代码,并添加了一些新的人员堡垒分类器
这是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>

答案 1 :(得分:1)

关于此jsfiddle code

的疑问

HTML部分
您有tbody中包含所有内容的表格。我用ththead分隔了行,并且有空的tbody。因为我需要分隔可单击的标题字段,并分隔可排序的内容。
重要的是在您想对其进行排序的列上添加类sortable。在这种情况下,所有列都是可排序的,除了第一个带有复选框的

JavaScript部分
我添加了var tbody = document.getElementById("resulttable_body");,最后所有行都添加到了空的tbody.appendChild(row);
市长的事是您创建了元素input并将输入追加到表格单元格,如下图所示:

enter image description here

我创建了 td 元素并将 input 放入其中

    //Multi Stage Checkbox creation
    tblCell = document.createElement('td');
    var input = document.createElement("INPUT");
    input.setAttribute("type", "checkbox");
    input.setAttribute("name", "");
    input.setAttribute("value", "");
    input.setAttribute("id", 1);
    tblCell.appendChild(input);
    tblCell.style.textAlign = 'center';
    row.appendChild(tblCell);