无需单击按钮即可自动加载文件
问题描述:
我是javascript新手,想要加载文件而不必单击加载文件按钮
I am new to javascript and want to load the file without having to click on the load file button
我正在使用以下脚本,并且希望文本自动在文本框中加载.
I am using the following script and I want the text to be loaded automatically in the text box.
<html>
<body>
<table>
<tr>
<td>Select a File to Load:</td>
<td>
<input type="file" id="fileToLoad">
</td>
<td>
<button onclick="loadFileAsText()">Load File</button>
<td>
</tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
</td></tr>
</tr>
</table>
</body>
</html>
<script type='text/javascript'>
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
预先感谢您的帮助.
答
尝试添加 onchange
属性,当对该输入进行更改时,它将调用函数.
Try adding the onchange
attribute, this will call functions when changes have been made to that input.
<input type="file" id="fileToLoad" onchange="loadFileAsText()">
演示
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
document.getElementById("inputTextToSave").value = fileLoadedEvent.target.result;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
<table><tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad" onchange="loadFileAsText()"></td>
<!-- ^^ onchange attribute added ^^ -->
</tr><tr>
<td colspan="2"><textarea id="inputTextToSave" style="width:512px;height:256px"></textarea></td>
</tr></table>
如果您对以上源代码有任何疑问,请在下面留下评论,我会尽快与您联系.
If you have any questions about the above source code please leave a comment below and I will get back to you as soon as possible.
我希望这会有所帮助.祝您编码愉快!
I hope this helps. Happy coding!