如何解决如何在绑定javascript后调用函数
大家好, 我需要帮助来解决我想在 epub 完全加载后调用函数的情况。
下面的代码成功加载了 epub,但我想显示目录 (toc),它在 epub 文件加载后实际显示在开发人员控制台中。 我一直无法显示 toc,LoadToc 从未被调用,当我改变它被调用的位置时,它会立即被调用,无需等待 epub 完全加载。
book = null;
document.getElementById('bookChooser').addEventListener('change',function(e) {
var firstFile = e.target.files[0];
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function(e) {
book = ePub({
bookPath: e.target.result
});
book.renderTo("area");
/* Replace area with the id for your div to put the book in */
}.bind(this).bind(this.LoadToc);
reader.readAsArrayBuffer(firstFile);
} else {
alert("Your browser does not support the required features. Please use a modern browser such as Google Chrome,or Mozilla Firefox ");
}
});
function LoadToc() {
if (book !== null) {
var results = book.toc;
var $select = document.getElementById("toc"),docfrag = document.createDocumentFragment();
var $select = document.getElementById("toc"),docfrag = document.createDocumentFragment();
results.forEach(function(chapter) {
var option = document.createElement("option");
option.textContent = chapter.label;
option.ref = chapter.href;
docfrag.appendChild(option);
});
$select.appendChild(docfrag);
$select.onchange = function() {
var index = $select.selectedIndex,url = $select.options[index].ref;
display(url);
return false;
};
}
}
document.getElementById("prev").onclick = function() {
book.prevPage();
}
document.getElementById("next").onclick = function() {
book.nextPage();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/epub.js/0.2.13/epub.min.js"></script>
<input type="file" id="bookChooser">
<select id="toc"></select>
<div id="area"></div>
<button id="prev" type="button"><</button>
<button id="next" type="button">></button>
解决方法
好的,我终于能够解决这个问题了。 文件读取器需要在调用函数之前结束。所以使用下面的代码解决了问题。
...
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function(e) {
book = ePub({
bookPath: e.target.result
});
book.renderTo("area");
/* Replace area with the id for your div to put the book in */
}.bind(this).bind(this.LoadToc);
reader.readAsArrayBuffer(firstFile);
reader.onloadend = () => {
LoadToc();
}
} else {
alert("Your browser does not support the required features. Please use a modern
browser such as Google Chrome,or Mozilla Firefox ");
}
...
对于任何可能面临此类问题的人 感谢所有评论的人
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。