javascript 中出现“无法读取 null 的属性‘addEventListener’”错误
2015-05-29
565
我有一个将文本保存到 txt 文件中的函数。 它可以独立运行(当我有一个简单的 html 和 js 文件时),但是当我将其添加到我的程序中时,它会引发此错误:
Cannot read property 'addEventListener' of null
(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个回答
我更新了你的代码,让它看起来更清晰,我删除了一些拼写错误,所以现在不会抛出任何错误。
我刚刚创建了函数 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));
ecarrizo
2015-05-29