簡體   English   中英

鏈接兩個 JavaScript 文件以在 HTML 頁面頂部一起工作

[英]Link two JavaScript files to work together on top of an HTML page

我的編程 class 有作業,這要求我使用 JS 類。 最重要的是,我必須使用 HTML 並且必須在單獨的.js 文件中定義這些類。 我已經完成了所有的工作,如果類是在同一個.js 文件上定義的,它運行正常,但是一旦我將代碼粘貼到不同的文件上,它就會停止工作。 我已經嘗試在主文件中導入類,但我可以讓它工作(我嘗試了不同的導入代碼,因為我在谷歌上找到了這個問題的不同答案但沒有人工作,這就是我在這里問的原因)。 我相信這可能是因為我在導入時做錯了,但我找不到錯誤。

盡管您的代碼有效,但將 js 文件保留在 HTML 的頂部會延遲頁面的加載時間。 在像家庭作業這樣的簡單場景中,無需擔心,但在大型項目中,它變得至關重要。

通過閱讀您的代碼,它只會在所有頁面都已加載時開始,因此無需將其放在頭部。

您是否嘗試過這樣做:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="first.js"></script>
    <script src="second.js"></script>

    <p>Hello World!</p>
</body>
</html>

首先,我將分享一些代碼。 這是我的 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;
    }
}

我會開始說,雖然我發現了這個問題,但我不明白為什么會這樣。

好的,正如您在最后一段代碼中看到的那樣,參數與 class 屬性同名。 如果我嘗試在第一個 JS 文件上復制代碼,它會毫無問題地工作,但是一旦我在單獨的 JS 文件上使用該代碼,它就會停止工作。 在觸摸了代碼的每一部分之后,我最終更改了參數名稱,使其與 class 屬性不同,現在看起來像這樣:

class Persona{
    constructor(_nombre, _seccion, _mail){
        this.nombre=_nombre;
        this.seccion=_seccion;
        this.mail=_mail;
    }
}

那里的代碼完全可以正常工作,無需更改文件的 rest 上的任何內容(第一個 JS 文件和 HTML 文件都沒有)。

如果有人比我更了解為什么會發生這種情況,請隨時編輯此答案。

感謝大家的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM