“无法在javascript中读取属性'addEventListener'的null”错误

时间:2015-05-29 16:56:21

标签: javascript addeventlistener

我有一个将文本保存到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>

1 个答案:

答案 0 :(得分:1)

我已经更新了您的代码,因此它看起来更清晰,我删除了一些拼写错误,因此它现在不会抛出任何错误。

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

(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));

Fiddle