无法读取属性'null"javascript错误

"Cannot read property 'addEventListener' of null" error in javascript

本文关键字:null javascript 错误 quot 读取 属性      更新时间:2023-09-26

我有一个将文本保存为txt文件的函数。它自己工作(当我有一个简单的html和js文件),但当我把它添加到我的程序它抛出这个错误:

无法读取null属性'addEventListener'

(function(view) {
    "use strict";
    var document = view.document, 
    $ = function(id) {
        return document.getElementById(id);
    }, 
    session = view.sessionStorage
    // only get URL when necessary in case Blob.js hasn't defined it yet
    , get_blob = function() {
        return view.Blob;
    }
    text = "slavik's text";
    save_file = $('saveFile'); 
    text_filename = "filename.txt";
    documemt.getElementById('saveFile').addEventListener("submit", function(event) {
        event.preventDefault();
        var BB = get_blob();
        saveAs(
            new BB(
                [text.value]
                , {type: "text/plain;charset=" + document.characterSet}
            )
            , (text_filename.value) + ".txt"
        );
    }, false);
    view.addEventListener("unload", function() {
        session.text = text.value;
        session.text_filename = text_filename.value;
    }, false);
}(self));

html部分:

<div id="leftColumn">
    <ul>
        <li><a href="#" onclick="vaucherEntry(); return false; showVauchers()">Vaucher Entry</a></li>
        <li><a href="#" onclick="settings(); return false;">Settings</a></li>
        <li><a href="#" onclick="about(); return false;">About</a></li>
        <!--<button type="submit" onclick="saveFile()" id='saveFile'>Save File</button>-->
        <form id="saveFile">
            <input type="submit" value="Save file"/>
        </form>
    </ul>
</div>

我已经更新了你的代码,所以它看起来更清晰,我删除了一些打字错误,所以它现在没有抛出任何错误。

我刚刚创建了函数savea,因为它在你的逻辑中是需要的,并且缺失了,所以检查与你的代码的差异并修复它。

(function(view) {
    "use strict";
    var saveAs = function(param1, param2, param3) {
        console.log('you should do something with this params:');
        console.log(param1, param2);            
    },
        document = view.document, 
        $ = function(id) {
            return document.getElementById(id);
        }, 
        session = view.sessionStorage,
        // only get URL when necessary in case Blob.js hasn't defined it yet
        get_blob = function() {
            return view.Blob;
        },
        text = "slavik's text",
        save_file = $('saveFile'),
        text_filename = "filename.txt";
    document.getElementById('saveFile').addEventListener("submit", function(event) {
        event.preventDefault();
        var BB = get_blob();
        saveAs(new BB([text], {type: "text/plain;charset=" + document.characterSet }), text_filename);
    }, false);
    document.addEventListener("unload", function() {
        session.text = text.value;
        session.text_filename = text_filename.value;
    }, false);
}(self));

小提琴