我有一個程序,基本上允許查看者輸入員工姓名和他們的薪水,然後點擊確認按鈕。當這個按鈕被擊中時,表格行和單元格將被添加到下表中的薪水和員工姓名中。現在,結果也按字母順序排序。但是,問題在於,只有在顯示createbody函數之後纔會對結果進行排序。因此,直到輸入新員工後纔會更新字母順序。我的目標是讓結果實時排序,或有一個單獨的按鈕,將結果排序。無論哪種方式都很好。有沒有人有解決這兩個問題的方法?碼列表如下:表格排序
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Table Entry </title>
</head>
<body>
<input type="text" id="fullName" value="" placeholder="Firstname"> :Enter employee name <br>
<input type="text" id="salary" value="" placeholder="Salary"> :Enter employee salary <br>
<input type="button" value="click me add to employee list" onclick="addToArray()"> <p> </p>
<input type="button" value="click me to sort employees" onclick="sortEm()"> <p> </p>
<div id="tablediv">
<table border="1" id="source" cellspacing="3" cellpadding="3">
<thead>
<tr> <th>Employee Name</th> <th>Employee Salary</th> </tr>
</thead>
<tbody id="sourceBody">
<tr><td> </td><td> </td></tr>
</tbody>
</table> </div>
<script type="text/javascript">
function sortEm() {
var tbl = document.getElementById('source');
var row = tbl.insertRow(1);
var cell1 = row.insertCell(0);
row.deleteCell(0);
document.getElementById("tbl").deleteRow(1);
}
var NameSalaries= [];
function addToArray() {
var fn = document.getElementById('fullName').value;
var sly = document.getElementById('salary').value;
var both = [fn,sly];
NameSalaries.push(both);
createBody(NameSalaries);
document.getElementById('fullName').focus();
NameSalaries.sort();
}
function createBody(NS) {
var tarr = [];
for (var i=0; i<NS.length; i++) {
tarr.push('<tr><td>'+NS[i][0]+'</td><td>'+NS[i][1]+'</td></tr>');
} document.getElementById('sourceBody').innerHTML = tarr.join('');
}
</script>
</body>
</html>
難道你不能在創建身體之前對名字薪水進行排序嗎?只需調用'NameSalaries.sort()',然後使用排序的數組創建主體。 –
嘗試在此處提問時儘可能多地提取您的用例。我們不需要了解「員工」,「工資」或查看整個html標記。我們只需要知道你必須渲染一個數組元素的排序數組;不必要的精度只會阻止人們閱讀。 –
你是對的christophe,謝謝你的提示! –