首先,我将分享一些代码。这是我的 HTML 头:
<head>
<meta charset="utf-8">
<title>Obligatorio1</title>
<link rel="stylesheet" href="css/estilos.css">
<script src="js/funciones.js"></script>
<script src="js/clases.js"></script>
</head>
这是我在第一个 JS 上的相关代码:
window.addEventListener('load',inicio)
function inicio(){
document.getElementById("botonAgregarPersonas").addEventListener("click",registroPersonas);
}
let personas=[];
function registroPersonas(){
let nombre=document.getElementById("nombrePersonas").value.trim();
let seccion=document.getElementById("seccionPersonas").value;
let mail=document.getElementById("emailPersonas").value.trim();
let esta=false;
for (i=0;i<personas.length&&!esta;i++){
if (nombre==personas[i].nombre) {
esta=true;
}
}
if (esta){
alert("Nombre ya ingresado");
}else {
let Per = new Persona (nombre, seccion, mail);
personas.push(Per);
let texto=Per.nombre+" - Sección: "+Per.seccion+" - "+Per.mail;
agregarElementoEnLista(texto);
agregarEnComboCompras(Per.nombre);
agregarCheckboxes(Per.nombre);
}
}
function agregarElementoEnLista (texto){
let nodoLi=document.createElement("LI");
let nodoTexto=document.createTextNode(texto);
nodoLi.appendChild(nodoTexto);
document.getElementById("lista").appendChild(nodoLi);
这是我的第二个 JS 文件(有类的那个)的代码:
class Persona{
constructor(nombre, seccion, mail){
this.nombre=nombre;
this.seccion=seccion;
this.mail=mail;
}
}
我会开始说,虽然我发现了问题,但我不明白为什么会发生。
好的,正如您在最后一段代码中看到的那样,参数与类属性具有相同的名称。如果我尝试在第一个 JS 文件上复制代码,它会毫无问题地工作,但是一旦我在单独的 JS 文件上使用该代码,它就会停止工作。在接触了代码的每一部分之后,我最终更改了参数名称,使其与类属性不同,现在看起来像这样:
class Persona{
constructor(_nombre, _seccion, _mail){
this.nombre=_nombre;
this.seccion=_seccion;
this.mail=_mail;
}
}
那里的代码运行良好,无需更改其余文件的任何内容(第一个 JS 文件和 HTML 文件都没有)。
如果有人比我更了解为什么会发生这种情况,请随时编辑此答案。
感谢大家的帮助!