【发布时间】:2014-10-22 13:46:18
【问题描述】:
实际上,我有一个带有注释的 HTML 学生表单,每次单击重定向到 anadirNota() 的按钮时。从输入txtNota 中获取值并添加到跨度spanNotas。当您单击anadirAlumno() 按钮时,将表单的值添加到表格的新行,但使用spanNotas(作为数组)通过obtenerMedia() 方法进行计算。
我的问题是:如何将 de spanNotas 元素作为 Ints 数组进行操作?
示例:
名称:Al 阿佩利多:巫统 注释:[2、6、8]
当我点击“añadir alumno”按钮插入行时:
Nombre | Apellidos | Media
Al | Umno | 5,33
HTML 代码:
<body>
Nombre:<input id="txtNombre" type="text" />
Apellido:<input id="txtApellido" type="text" />
Notas: [<span id="spanNotas"></span>]
<br/>
Nota:<input id="txtNota" type="text" />
<input type="button" value="Añadir nota" onclick="anadirNota()"/>
<br/><br/>
<input type="button" value="Añadir alumno" />
<br/><br/>
<table id="tablaAlumnos">
<tr>
<th>Nombre</th>
<th>Apellido</th>
<th>Media</th>
</tr>
</table>
</body>
Javascript 代码:
function anadirNota() {
var nota = parseInt(document.getElementById("txtNota").value);
console.log(nota);
if(!isNaN(nota)) {
var listaNotas = document.getElementById("spanNotas").innerHTML;
console.log(listaNotas);
listaNotas += nota;
console.log(listaNotas);
document.getElementById("spanNotas").innerHTML=listaNotas+", ";
} else {
alert("El valor del campo nota no es válido")
}
}
function anadirAlumno() {
var nombre = document.getElementById("txtNombre").value;
var apellido = document.getElementById("txtApellido").value;
var notas = document.getElementById("spanNotas").innerHTML;
if(nombre != "" || apellido != "" || notas.isEmpty ) {
var Alumno1 = new Alumno(nombre, apellido, notas);
var notaMedia = Alumno1.obtenerMedia();
console.log(Alumno1);
var table = document.getElementById("tablaAlumnos");
fila = table.insertRow(table.length);
fila.insertCell (0).innerHTML=nombre;
fila.insertCell (1).innerHTML=apellido;
fila.insertCell (2).innerHTML=notaMedia;
} else {
alert("Los datos del alumno no son correctos")
}
}
var Alumno = function(nombre, apellido, notas)
{
this.nombre = nombre;
this.apellido = apellido;
this.notas = notas;
this.obtenerMedia = function() {
var media = 0;
for(i = 0; i < this.notas.length; i++)
media += this.notas[i];
media /= this.notas.length;
return media.toFixed(2);
};
};
</script>
【问题讨论】:
-
问题是,你的
listaNotas是一个字符串。定义一个全局变量Array();而不是+=使用push()函数。
标签: javascript html arrays getelementbyid