如何从HTML调用另一个文件中定义的javascript函数?

时间:2019-04-20 01:06:09

标签: javascript html

我正在尝试编写网站,但是当我尝试从HTML代码调用另一个文件中定义的JavaScript函数时,出现以下错误

  

未捕获的ReferenceError:未在admin.html:46上定义fetchConfs

我确实将脚本导入了HTML的<head>部分,但是由于某些原因,我仍然遇到错误。

admin.html:

<!DOCTYPE html>
<head>    
    <link rel="stylesheet" href="bundle.css">
    <script type="text/javascript" src="bundle.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script> 
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-firestore.js"></script>
    <title>Dilo+</title>
</head>
<header class="header">
    <img src="logo.png">
    <p>Sobreviviendo a lo imposible</p>
</header>

<body>
    <script type="text/javascript">
        var firebaseConfig = {
            apiKey: "",
            authDomain: "dilo-mas.firebaseapp.com",
            databaseURL: "https://dilo-mas.firebaseio.com",
            projectId: "dilo-mas",
            storageBucket: "",
            messagingSenderId: ""
        };
        firebase.initializeApp(firebaseConfig);
        initApp = function () {
            firebase.auth().onAuthStateChanged(function (user) {
                if (user) {
                    var email = user.email;
                    user.getIdToken().then(function (accessToken) {
                        document.getElementById("greeter").textContent = "Hola " + email;
                    });
                } else {
                    window.location.href = '/login.html'
                }
            }, function (error) {
                console.log(error);
            });
        };
        window.addEventListener('load', function () {
            initApp()
            document.getElementById("logout").onclick = function logout() {
                firebase.auth().signOut().then(function () { window.location.href = '/login.html' });
            }
            var confs = fetchConfs();
        });
    </script>
    <h1 id="greeter">Error, inicia sesión para continuar</h1>
    <button class="mdc-button foo-button" id="logout" style="float: right;">
        Cerrar Sesión
    </button>
</body>
</html>

app.js(此文件在部署前已使用webpacks编译为bundle.js):

import {MDCRipple} from '@material/ripple/index';
import { MDCTextField } from '@material/textfield';
import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/firebase-auth';

const ripple = new MDCRipple(document.querySelector('.foo-button'));

var firebaseConfig = {
    apiKey: "",
    authDomain: "dilo-mas.firebaseapp.com",
    databaseURL: "https://dilo-mas.firebaseio.com",
    projectId: "dilo-mas",
    storageBucket: "",
    messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);

document.getElementById("tbut").onclick = function submitForm() {
    var date = Date.now().toString()
    var x = document.getElementById("conf").value;
    firebase.firestore().collection("confesiones").doc(date).set({
        conf: x
    })
        .then(function () {
            console.log("Document successfully written!");
            var y = document.getElementById("conf").value;
            console.log("input " + x)
            alert("Exito");
        })
        .catch(function (error) {
            console.error("Error writing document: ", error);
            alert("Error envíando tu confesión")
        });
    document.getElementById("conf").reset();
}

function fetchConfs() {
    var confs = db.collection("confesiones").where(firebase.firestore.FieldPath.documentId(), "!=", "root").get();
    return confs;
}

我已经尝试将fetchConfs()分配给窗口对象或全局变量,但是仍然遇到相同的错误。

注意:我正在使用webpack和其他npm插件将js和sass代码编译为静态文件以进行部署。

1 个答案:

答案 0 :(得分:0)

脚本按照在<head>中列出的顺序运行,然后在正文中依次运行。如果该功能在后面列出的脚本中,则该功能在运行时可能尚未定义。

要解决此问题,请在前面定义fetchConfs