无需单击按钮即可自动加载文件 [英] Load a file automatically without using a click button

查看:52
本文介绍了无需单击按钮即可自动加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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!

这篇关于无需单击按钮即可自动加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆