我希望你能用一个小的javascript程序帮助我,当我向数组添加元素(客户及其类型)时,我的程序似乎工作正常,但我不知道如何在可观察数组旁边添加按钮元素,以便用户可以逐个删除他们想要的条目?下图显示了我希望程序看起来像什么:!非常感谢!
function addCustomer()
{
var newIndex = customerList.length;
customerList[newIndex] = new Object;
customerList[newIndex].name = document.getElementById('name').value.trim();
customerList[newIndex].childOrAdult = childOrAdult.options[childOrAdult.selectedIndex].value;
displayCustomers();
}
function displayCustomers()
{
var message = '';
var message = '<tr><td><b> CUSTOMER NAME </b></td><td><b> CHILD/ADULT </b></td></tr>\n';
for (var i = 0 ; i < customerList.length ; i++)
{
message += '<br><tr><td> ' + customerList[i].name + ' </td><td> '
+ String(customerList[i].childOrAdult) + ' </br></td></tr>\n';
}
document.getElementById('outputDiv').innerHTML = message;
}
&#13;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<title>Giant Trampoline Customers</title>
<script src="" type="text/javascript"></script>
</head>
<body onload="displayCustomers();">
<h1 style="text-align: center;">Giant Trampoline Customers</h1>
<div id="outputDiv" style="text-align: center;"></div>
<br>
<div id="inputDiv" style="text-align: center">
<h3>Add A Customer:</h3>
New customer's name: <input type="text" id="name" maxlength="30" value="" size="30">
</select>
<button type="button" onclick="addAndDisplayCustomer();">add</button>
</div>
</body>
</html>
&#13;
![期望的结果] [1]
答案 0 :(得分:0)
jsFiddle demo (http://jsfiddle.net/json/asdzgst9/)
首先,如果要在表格中显示数据,可能需要将<div id="outputDiv">
替换为<table>
。所以,
<div id="outputDiv" style="text-align: center;"></div>
变为:
<table id="outputTable" style="text-align: center;"></table>
其次,您需要更新显示customerList
中所有元素的功能,以便使用按钮呈现额外的表格列。
function displayCustomers() {
var message = '<tr><td><b> CUSTOMER NAME </b></td><td><b> CHILD/ADULT </b></td><td></td></tr>';
for (var i = 0 ; i < customerList.length ; i++) {
message += '<tr><td> ' + customerList[i].name + ' </td>';
message += '<td>' + customerList[i].childOrAdult + ' </td>';
// Here, create a third column with a button.
message += '<td><button onclick="removeCustomer(' + i + ')">remove this customer</button></td></tr>';
}
// Note: we have replaced the outputDiv with outputTable here!
document.getElementById('outputTable').innerHTML = message;
}
第三,一个处理单击新按钮并通过提供的索引从列表中删除元素的函数。
function removeCustomer(index) {
// remove 1 element from the array customerList from the given index.
customerList.splice(index, 1);
displayCustomers();
}
<强>分拣强>
要对数组进行排序,您可以调用a build-in method sort
。查看更新的 jsFiddle demo (http://jsfiddle.net/json/asdzgst9/)
更新函数displayCustomers
并在for
循环之前添加以下代码段:
customerList.sort(function (customerA, customerB) {
if (customerA.name < customerB.name) {
return -1;
} else if (customerA.name > customerB.name) {
return 1;
} else {
return 0;
}
});