簡體   English   中英

如何阻止JavaScript生成HTML文件,其中只有一個JS函數調用

[英]How to stop JavaScript from generating an HTML file with nothing but a JS function call in it

在javascript文件中使用EventListener來調用函數document.getElementById("messageSubmit").addEventListener("click", getKey)但是,在運行我的代碼時,JS會拋出一個ReferenceError,說明沒有定義getKey()(它並且,為了告訴我發生錯誤的位置,請將我指向index.html ,它現在只包含一行: getKey() 在查看Inspect Element中的文件時,我的原始index.html就在那里,並且完好無損。 究竟發生了什么,我該如何解決它?

我試圖改變getKeygetKey()在事件監聽,我曾嘗試刪除新的文件,但是我的IDE無法識別新的文件存在,或曾經存在。 (我的IDE是JetBrains的WebStorm)我不會發布整個JS文件,因為它是~50000行,但這里有問題的功能和調用。

async function startChat(user, userkey, userPubKey, oUID, position) { //Will start an encrypted chat between two users FIXME: Needs rewriting
    targetUID = oUID;
    var localUID = user.uid;
    console.log(position);
    var order = position === "true" ? localUID + " " + targetUID : targetUID + " " + localUID;
    console.log(order);
    var accepted;
    await database.ref("/chats/" + order + "/accepted/" + targetUID + "/").once('value', function(snapshot) {
        if(snapshot.val() != null) {
            accepted = snapshot.val();
        }
    });
    if (accepted === "true") {
        database.ref("/chats/" + order + "/" + localuuid + "/messages/").on("child_added", (data, prevChildKey) => {
            var newpost = data.val();
            console.log(newpost);
            Object.keys(newpost).sort();
            console.log(newpost);
            const ordered = Object.keys(newpost).sort();
            // Object.keys(newpost).map((key, index) => {
            //
            //
            // }).catch( (error) => {
            //     console.log(error.message);
            //     console.log(error.code);
            // });
            console.log(newpost['message']); //{Prints encrypted message(all messages looped)
            console.log(newpost['date']);//Prints date stamp(all messages looped)
            console.log(newpost['time']);//Prints time stamp(all messages looped)
            console.log(newpost['sender']);//Prints sender uid(all messages looped)
            //var decrypt = cryptico.decrypt(newpost['message'], userkey).plaintext;

            // noinspection JSJQueryEfficiency
            $("#chatField").append("<span>" + newpost['sender'] + "</span>");
            // noinspection JSJQueryEfficiency
            $("#chatField").append("<span>" + newpost['time'] + "</span>");
            // noinspection JSJQueryEfficiency
            $("#chatField").append("<span>" + newpost['message'] + "</span>");
        }).catch( (error) => {
            console.log(error.message);
            console.log(error.code);
        });
    } else {
        var myRef = firebase.database().ref("/chats/" + order + "/accepted/" + oUID).set("false");
    }

document.getElementById("listHere").addEventListener("click", startChat);

錯誤:

index.html:1 Uncaught ReferenceError: getKey is not defined
    at HTMLAnchorElement.onclick (index.html:1)

單擊鏈接的index.html文件,它顯示:

getKey();

沒有別的。

我如何解決這個問題,或者,如果沒有辦法,是否有解決方法? 編輯:有人要求HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="ChatLayoutStyleSheet.css">
    <title>ChatLayout</title>
    <script src="cryptico/cryptico-js-master/lib/cryptico.js"></script>
</head>
<body>
    <ul>
        <li><a class="active" href="index.html">Home</a></li>
        <li><a href="InfoPage.html">Information</a></li>
        <li><a href="chatlayout.html">Chat</a></li>
        <li><a href="ChatLayoutGC.html">Groupchat</a></li>
        <li><a href="signin.html">Sign In</a></li> <!-- DON'T TOUCH THIS -->
        <li><a href="signup.html">Sign Up</a></li> <!-- DON'T TOUCH THIS EITHER -->
    </ul>

    <h1 style = "color: white;" id= "title">Welcome To Your Private Chat Room!</h1>
    <h3 style = "color: white;" id="chatName">Invite your friends to start chatting</h3>
    <div class = center2 id="chatField">Display Text Here</div>

    <div class= center>
        <label for="sendmessage" id="messageLabel">Send Message</label>
        <input id="sendmessage" type="text" name="Type" placeholder="Type Here"><br>
        <button type="submit" value="Send" id="messageSubmit">Send</button>
    </div>
    <div id="newchat">
            <label for="findEmail" class="findChat">Search Emails</label>
            <input id="findEmail" type="email" class="findChat">
            <input id="findEmailSubmit" class="findChat" onclick="//parseSearchedEmails()" type="submit">

        <button id="listHere" onclick=""></button>
        <!-- ENCRYPTION PASSPHRASE INPUT REMOVED. DO NOT ADD THAT BACK. THANK YOU. -->
    </div>
</body>
<footer>
    <script src="bundledCHATJS.js" type="text/javascript"></script>
</footer>
</html>

這聽起來像是一個范圍問題(但無法通過提供的元素進行確認和解決)。 這是一個非常基本的示例,帶有一個原始閉包,可以導出到全局范圍(基本的Web應用程序noawadays)來演示:

 // Simulate a bundle with some exports (function(global) { function t1() { alert('Success : all is done in the closure scope'); } function t2() { alert('Fails : callback not available in event setter scope'); } // Exports to global scope global.t3 = function() { alert('Success : callback is exported to event setter scope'); }; // This will be set up within closure scope. It works document.getElementById('test1').addEventListener('click', t1); })(window) // This will be set up within window scope and t3 available. It works document.getElementById('test3').addEventListener('click', t3); // This will be called within window scope and t2 not available. It fails. document.getElementById('test2').addEventListener('click', t2); 
 <button id="test1">test 1 (OK)</button> <button id="test2">test 2 (KO)</button> <button id="test3">test 3 (OK)</button> 

t2確實存在但在設置事件回調時在當前范圍內不可用,因此not defined錯誤。 解決此問題的唯一方法是檢查代碼結構。

我不習慣Webstorm,有點假的index.html可能只是調試器中的一個工件。 你提供的JS代碼是無用的,它是錯誤的HTML元素id( listHere而不是messageSubmit ),並且看不到getKey

順便說一句,如果你使用addEventListener('click', myFunc())而不是addEventListener('click', myFunc) ,它將在設置監聽器時運行回調,而不是在事件發生時運行。

暫無
暫無

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

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