【发布时间】:2019-07-27 00:06:32
【问题描述】:
我想在我的表中总计一列。我的数组列表包含两个对象并使用该数组中的函数生成一个表。我对一个特定列(英里数)求和的功能没有向我的网页输出任何内容。我想点击获取状态,显示总里程数。
我尝试将提到的代码放在一个单独的函数中,但它不起作用。
<body>
<label>Please enter your flight Number:</label><br>
<input type="text" id="flightNumber" name="flightnumber" value="" /> <br />
<label>Please enter Miles Flown:</label><br>
<input type="text" id="milesFlown" name="milesflown" value="" />
<br>
<input type="button" id="display" name="display" value="Submit Flight Information" />
<br>
<div id ="classMessages"></div>
<input type="button" id="status" name="status" value="Get Class Status" onclick= getClassStatus(); />
<table id="flightTable">
<tr>
<th>Flight Number</th>
<th>Miles Flown</th>
</tr>
</table>
</div>
<script type="text/javascript">
const flightTable = document.getElementById('flightTable'),
button = document.getElementById('display'),
flightNum = document.getElementById('flightNumber'),
milesFlown = document.getElementById('milesFlown'),
addRow = () => {
const tr = document.createElement('tr'),
tdFlightNo = document.createElement('td'),
tdMilesFlown = document.createElement('td');
tdMilesFlown.setAttribute('class', 'needsToBeCounted');
/** getting the last record in the flight objects array **/
tdFlightNo.textContent = flightArray[i - 1].flightNumber;
tdMilesFlown.textContent = flightArray[i - 1].milesFlown;
/** append the TDs elements to the TR element (all of them are created above dynamically) **/
tr.append(tdFlightNo, tdMilesFlown);
/** append that row to the HTML table **/
flightTable.appendChild(tr);
}
let flightArray = [],
flightNumValue = null,
milesFlownValue = null,
i = 0;
button.addEventListener('click', () => {
flightNumValue = flightNum.value;
milesFlownValue = milesFlown.value;
/** checking for duplicate entry **/
if (flightArray.find(el => {
return el.flightNumber === flightNumValue
})) {
alert('You cannot enter this flight due to Duplicate Flight Number entry: "' + flightNumValue + '"');
return false;
}
/** add the entry in the flight objects table **/
flightArray[i++] = {
flightNumber: flightNumValue,
milesFlown: milesFlownValue
}; /** add the flight record to the array and increment the counter i (notice the i++) **/
addRow(); /** call addRow to add a new row in the table (HTML) **/
});
function getClassStatus(){
var cls = document.getElementById("flightTable").getElementsByTagName("td");
for (var i = 0; i < cls.length; i++){
if(cls[i].className == "needsToBeCounted"){
total += isNaN(cls[i].innerHTML) ? 0 : parseInt(cls[i].innerHTML);
}
console.log(total);
</script>
Uncaught ReferenceError: getClassStatus is not defined 点击我的按钮计算里程。
【问题讨论】:
标签: javascript arrays