【问题标题】:How do I remove an upload item from a form?如何从表单中删除上传项目?
【发布时间】:2013-04-14 12:21:31
【问题描述】:

我有一个允许使用文件输入加载文件的表单。我想允许用户删除上传项目,但我无法弄清楚。到目前为止,这是我尝试做的事情:

<form action="insert.php" method="POST" align="right" id="post_form">
 <input type="file" id="upload_file" onChange="display()">
 <div id="show_button" onClick="remove_pic()">  remove </div><br>
</form>


function remove_pic() {
  alert('check');
  var file_loaded = document.getElementById("upload_file");
  file_loaded = null; // here i try to remove the object
}

【问题讨论】:

    标签: javascript file upload


    【解决方案1】:

    通过 JSFiddle 运行您的代码并检查 Chrome 开发控制台后,我不断收到“未定义函数”错误消息。

    我发现,将您尝试直接调用的函数显式放入全局范围可以使其被识别为已定义。您还需要使用空白字符串而不是 null 并将对“.value”属性的更改附加到“file_loaded”变量中。

    代替

    function remove_pic() {
      alert('check');
      var file_loaded = document.getElementById("upload_file");
      file_loaded = null; // here i try to remove the object
    }
    

    试试

    window.remove_pic = function() {
      alert('check');
      var file_loaded = document.getElementById("upload_file");
      file_loaded.value = ""; // here i try to remove the object 
    };
    

    示例 JSFiddle:http://jsfiddle.net/xu6SD/1/

    【讨论】:

    • 嗨,实际上我所要做的就是将 .value 添加到 file_loaded。你能解释一下为什么要写这个:“window.remove_pic = function()”我的意思是这行是什么意思?
    • 这可能只是 JSFiddle 的一个怪癖,但似乎我必须明确地将函数放入全局范围才能使其工作。据我了解,编写“window.remove_pic = function()”只是将函数纳入全局范围的一种明确方式。我还从JavaScript: The Good Parts 中学习了“var functionName = function()”——他的论点是它使函数的定义更清晰、更易于阅读。不过,很高兴它起作用了! :)
    猜你喜欢
    • 2023-01-17
    • 1970-01-01
    • 2014-03-01
    • 2016-03-12
    • 2021-08-11
    • 1970-01-01
    • 2019-06-05
    • 2021-10-19
    相关资源
    最近更新 更多