我有一个textarea用于输入行和列(但不是表)的值,我希望能够单独添加行的值。我的逻辑是,我让用户输入他们输入的行数,将输入拆分为一个字符串,然后按照他们输入的行数将其拆分。这就是我所拥有的。很高兴能有更好的解决或者,我做了一些阅读,并认为我可以将行转换为实际<tr>
s然后通过它们(我也希望能够在以后的阶段为列提供此功能)。提前致谢:
<html>
<head>
<script type='text/javascript'>
function sum(){
var rows= document.getElementById('rows').value;
var val = document.getElementById('userInput').value;
var temp = val.split(" ");
var lines=temp.split(rows);
var total = 0;
var v;
for(var i = 0; i < temp.length; i++) {
v = parseFloat(lines[i]);
//this is what I am missing to get each row's sum separately
}
document.write(//each row total);
}
</script>
</head>
<body>
<form id="input">
<textarea id="userInput"></textarea>
Number of rows: <textarea id="rows"></textarea>
<input id="Run" type=Button value="run" onClick="sum()" />
</form>
</body>
</html>
所以现在我有以下内容(我不得不重新添加v),但它返回NaN(并注意到我将解决最终的建议):
<script type='text/javascript'>
function sum() {
var grandTotal = 0,
rowTotals = [], // array to hold individual row totals
rowData,
rows,
val,
var v;
rawData = document.getElementById('userInput').value;
rows = rawData.split("\n");
for (var i=0; i < rows.length; i++) {
rowTotals[i] = 0;
rowData = rows[i].split(" ");
for (var j=0; j < rowData.length; j++) {
val = parseFloat(rowData[j]);
if (!isNaN(v)) rowTotals[i] += v;
}
alert("Total for row " + (i + 1) + ": " + rowTotals[i]);
grandTotal += rowTotals[i];
}
alert("Grand total: " + grandTotal);
}
</script>
答案 0 :(得分:1)
假设用户输入了以下格式的数据:
12.1 4.8 11.2 4.1
1.2 3.4 5.6 99.9
etc
也就是说,如果每行末尾有一个新行和数字之间的空格,那么你可以这样做:
function sum() {
var grandTotal = 0,
rowTotals = [], // array to hold individual row totals
rowData,
rows,
val,
rawData = document.getElementById('userInput').value;
// if desired replace this comment with regex validation of rawData
rows = rawData.split("\n");
for (var i=0; i < rows.length; i++) {
rowTotals[i] = 0;
rowData = rows[i].split(" ");
// if you need to test that each row has the same number
// of values in it do that here
for (var j=0; j < rowData.length; j++) {
val = parseFloat(rowData[j]);
// add validation of val here
rowTotals[i] += val;
}
alert("Total for row " + (i + 1) + ": " + rowTotals[i]);
grandTotal += rowTotals[i];
}
// at this point rowTotals is an array containing
// the individual row totals, so do what you like with that
alert("Grand total: " + grandTotal);
}
在功能中有两点需要做更多的工作:
parseFloat()
的结果是否实际上是一个数字 - 用户可能输入了字母字符或标点符号,在这种情况下它会返回NaN
。或者,在执行任何其他操作之前,使用正则表达式来验证整个字符串的格式和非法字符。我将这两点作为练习留给读者......